首页 > 解决方案 > 将值从数据库传递到 JS React 中的翻转卡片

问题描述

我正在尝试将我的 API 值传递给 Flippy 卡以动态呈现图像和翻转时显示的单词。

我正在努力解决我认为很容易的事情:我有一个 API,我可以在其中回调一个图像链接和一个单词来填充翻转卡片。我想使用该数据动态地将我的翻转卡片呈现到页面,但现在我的图像链接和单词是硬编码的,我不知道将我的 API 调用值传递给组件。API 工作并正确返回链接和单词;硬编码的翻盖卡也可以正常工作,没有问题,功能也符合预期。我相信我必须实现道具并以某种方式将其传递给 const DefaultCardContents - 非常感谢您尝试一下。

我尝试实现道具,但我不确定如何将它们传递给常量

这是我的抽认卡组件

import React, { Component } from 'react';
import Flippy, { FrontSide, BackSide } from './../lib';
import Button from 'react-bootstrap/Button';
import './style.css';
const FlippyStyle = {
width: '200px',
height: '200px',
textAlign: 'center',
color: '#FFF',
fontFamily: 'sans-serif',
fontSize: '30px',
justifyContent: 'center'
}

const DefaultCardContents = ({ children }) => (
<React.Fragment>
<FrontSide
style={{
backgroundColor: 'white',
display: 'flex',
alignItems: 'center',
flexDirection: 'column'
}}
>
<img
src="https://parent.guide/wp-content/uploads/2014/08/Banana-baby-food-recipes.jpg"
style={{ maxWidth: '100%', maxHeight: '100%' }}
/>
<span
style={{
fontSize: '12px',
position: 'absolute',
bottom: '10px',
width: '100%'
}}>
{children}<br />
Hover over to show key word
</span>
</FrontSide>
<BackSide
style={{
backgroundColor: '#EB6864',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
flexDirection: 'column'
}}>
<h1>Banana</h1>
<span
style={{
fontSize: '12px',
position: 'absolute',
bottom: '10px',
width: '100%'
}}>
{children}<br />
<Button variant="success">Success</Button>
<Button variant="outline-warning">Warning</Button>
</span>
</BackSide>
</React.Fragment>);
const FlippyOnHover = ({ flipDirection = 'vertical' }) => (
<Flippy
flipOnHover={true}
flipDirection={flipDirection}
style={FlippyStyle}
>
<DefaultCardContents>
</DefaultCardContents>
</Flippy>
);
class Flashcard extends Component {
constructor(props) {
super(props);
this.state = {
isFlipped: false
}
}
render() {
return (
<div className="App">
<div style={{ display: 'flex', flex: '1 0 200px', justifyContent: 'space-around', 'flex-wrap': 'wrap' }}>
<FlippyOnHover flipDirection="horizontal" />
</div>
</div>
);
}
}
export default Flashcard;

这是我的 API 调用和页面渲染

 import React, { Component } from "react";
import Flashcard from "../components/Flashcard";
import API from "../utils/API";

class Flashcards extends Component {

  state = {
    flashcards: [],
    flashcardName: "",
    flashcardImage: "",
    flipped: false
  };

  componentDidMount() {
    this.loadFlashcards();
  };

  loadFlashcards = () => {
    API.getFlashcards()
      .then(res => {
        // console.log(res.data);
        this.setState({ flashcards: res.data, flashcardName: "", flashcardImage: "" })
        // console.log("flashhhhhhhhhh" + JSON.stringify(this.state.flashcards));
      })
      .catch(err => console.log(err));
  };

  flipped = () => {
    console.log(this.state)
    if (this.state.flipped === false) {
      this.setState({ flipped: true })
    }
  }

  render() {
      return (
        <div>
          {this.state.flashcards.length ? (
            <div>
              {this.state.flashcards.map(flashcards => (
                <div key={flashcards._id} >
                  <Flashcard/>
                </div>
              ))}
            </div>
          ) : (
              <h3>No Results to Display</h3>
            )}
        </div>
      )
    }
}

export default Flashcards;

Expected result is a dynamically generated array of cards base don API

标签: javascriptreactjsreact-props

解决方案


您需要修改您的Flashcard组件以接受标题的道具和图像的 URL,假设它们在从 API 返回的数据中。

在您的地图中,将值传递给Flashcard,例如:

{this.state.flashcards.map(flashcard => (
  <div key={flashcard._id}>
    <Flashcard
      title={flashcard.title}
      imageUrl={flashcard.image}
    />
  </div>
))}

编辑:

看起来您正在使用 react-flippy 库,因此您无需管理闪存卡的状态。

粗略地说,您的FlashCard组件可能类似于:

import React, { Component } from "react";
import Flippy, { FrontSide, BackSide } from "./../lib";
import Button from "react-bootstrap/Button";
import "./style.css";
const FlippyStyle = {
  width: "200px",
  height: "200px",
  textAlign: "center",
  color: "#FFF",
  fontFamily: "sans-serif",
  fontSize: "30px",
  justifyContent: "center"
};

const CardContents = ({ title, imageUrl }) => (
  <React.Fragment>
    <FrontSide
      style={{
        backgroundColor: "white",
        display: "flex",
        alignItems: "center",
        flexDirection: "column"
      }}
    >
      <img
        src={imageUrl}
        style={{ maxWidth: "100%", maxHeight: "100%" }}
      />
      <span
        style={{
          fontSize: "12px",
          position: "absolute",
          bottom: "10px",
          width: "100%"
        }}
      >
        <br />
        Hover over to show key word
      </span>
    </FrontSide>
    <BackSide
      style={{
        backgroundColor: "#EB6864",
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
        flexDirection: "column"
      }}
    >
      <h1>{title}</h1>
      <span
        style={{
          fontSize: "12px",
          position: "absolute",
          bottom: "10px",
          width: "100%"
        }}
      >
        <br />
        <Button variant="success">Success</Button>
        <Button variant="outline-warning">Warning</Button>
      </span>
    </BackSide>
  </React.Fragment>
);

class Flashcard extends Component {
  render() {
    return (
      <div>
        <div
          style={{
            display: "flex",
            flex: "1 0 200px",
            justifyContent: "space-around",
            "flex-wrap": "wrap"
          }}
        >
          <Flippy flipOnHover={true} flipDirection='horizontal' style={FlippyStyle}>
            <CardContents imageUrl={this.props.imageUrl} title={this.props.title}/>
          </Flippy>
        </div>
      </div>
    );
  }
}
export default Flashcard;


推荐阅读