【发布时间】:2020-11-20 05:42:09
【问题描述】:
我正在尝试制作一款卡鲁塔风格的纸牌配对游戏。
随机选择一张卡片并显示在页面顶部。
所有其他卡片显示在下方。
这些卡片是从带有 "id" (number), "front" (string), "back" (string) 的 JSON 中提取的。
预期结果:
- 点击下方卡片。
- 如果较低卡的 id(?) == 较高卡的 id, score++, 生成新的购物车。
我不确定如何实际比较这两者。如何从子组件中获取信息以与父状态进行比较?我不确定如何使用 handleComparison() 函数在此处找到特定单击的 div 的“x”。
//if (this.props.card[x].id == this.props.currentCard[0].id) {-> score++ -> 生成新卡}
import React from "react"
import Header from "./Header"
import { cardData } from "../Cards";
class GameContainer extends React.Component {
constructor(props) {
super(props);
this.state = {
cards: cardData,
score: 0,
currentCard: [{}],
}
}
componentDidMount = (e) => {
const random = Math.floor(Math.random() * cardData.length);
this.setState({
currentCard: [cardData[random]]
})
}
handleComparison = (e) => {
//if (this.props.card[x].id == this.props.currentCard[0].id) -> {score++ - > gen new card}
console.log('success');
}
render() {
return (
<div className="wrapper">
<Header score={this.state.score} />
<div className="currentCard" >
<p>{this.state.currentCard[0].front}</p>
</div>
<CardContainer cards={this.state.cards} handleComp={this.handleComparison}/>
</div>
)
}
}
class CardContainer extends React.Component {
render() {
return (
<div id="CardContainer" className="cardContainer">
{this.props.cards.map((cards, index) => (
<div id="card" className="card" onClick={this.props.handleComp}>
<p key={index}>{cards.back}</p>
</div>
))}
</div>);
}
}
export default GameContainer
【问题讨论】: