Reactjs 将特定子div与父状态数据进行比较

Reactjs 将特定子div与父状态数据进行比较,reactjs,use-state,Reactjs,Use State,我想做一个卡鲁塔式的卡片匹配游戏。 随机选择一张卡片并显示在页面顶部。 下面显示所有其他卡片。 这些卡片是从一个JSON中提取的,JSON带有“id”(数字)、“front”(字符串)、“back”(字符串) 预期结果: 单击下卡 如果较低卡的id(?)=较高卡的id,得分++, 生成新购物车 不过,我不知道如何比较这两者。如何从子组件获取信息以与父组件状态进行比较?我不确定如何使用handleComparison()函数在此处找到特定单击div的“x” //如果(this.props.ca

我想做一个卡鲁塔式的卡片匹配游戏。 随机选择一张卡片并显示在页面顶部。 下面显示所有其他卡片。 这些卡片是从一个JSON中提取的,JSON带有
“id”(数字)、“front”(字符串)、“back”(字符串)

预期结果:

  • 单击下卡
  • 如果较低卡的id(?)=较高卡的id,得分++, 生成新购物车
不过,我不知道如何比较这两者。如何从子组件获取信息以与父组件状态进行比较?我不确定如何使用handleComparison()函数在此处找到特定单击div的“x”

//如果(this.props.card[x].id==this.props.currentCard[0].id){->score++->gen new card}

从“React”导入React
从“/Header”导入标题
从“./Cards”导入{cardData};
类GameContainer扩展了React.Component{
建造师(道具){
超级(道具);
此.state={
卡片:cardData,
分数:0,
当前卡:[{}],
}
}
组件安装=(e)=>{
const random=Math.floor(Math.random()*cardData.length);
这是我的国家({
currentCard:[cardData[随机]]
})
}
手工比较=(e)=>{
//如果(this.props.card[x].id==this.props.currentCard[0].id)->{score++->gen new card}
console.log('success');
}
render(){
返回(
{this.state.currentCard[0].front}

) } } 类CardContainer扩展了React.Component{ render(){ 返回( {this.props.cards.map((卡片,索引)=>(

{cards.back}

))} ); } } 导出默认游戏容器
您可以从子组件传递值

<CardContainer cards={this.state.cards} handleComp={() => this.handleComparison(whatever_value_you_want_here)}/>

可以从子组件传递值

<CardContainer cards={this.state.cards} handleComp={() => this.handleComparison(whatever_value_you_want_here)}/>

您已经接近解决方案了。 你所需要的只是将道具从孩子传递给父母,然后点击卡片的
onClick

重写的代码将被删除

class CardContainer扩展了React.Component{
render(){
返回(
{this.props.cards.map((卡片,索引)=>(
这个.props.handleComp(卡片)}>

{card.back}

))} ); } }
然后在
handleComp
方法中将其保存到状态

class GameContainer扩展了React.Component{
建造师(道具){
超级(道具);
此.state={
卡片:cardData,
分数:0,
当前卡:[{}],
}
}
// ====
手牌比较=(卡片)=>{
//如果(card.id==this.state.currentCard[0].id)->{score++->gen new card}
console.log('success');
}
// ====
}

您已经接近解决方案了。 你所需要的只是将道具从孩子传递给父母,然后点击卡片的
onClick

重写的代码将被删除

class CardContainer扩展了React.Component{
render(){
返回(
{this.props.cards.map((卡片,索引)=>(
这个.props.handleComp(卡片)}>

{card.back}

))} ); } }
然后在
handleComp
方法中将其保存到状态

class GameContainer扩展了React.Component{
建造师(道具){
超级(道具);
此.state={
卡片:cardData,
分数:0,
当前卡:[{}],
}
}
// ====
手牌比较=(卡片)=>{
//如果(card.id==this.state.currentCard[0].id)->{score++->gen new card}
console.log('success');
}
// ====
}
  handleComparison = (whatever_value_you_want_here) => {
    //if (this.props.card[x].id == this.props.currentCard[0].id) -> {score++ - > gen new card}

      console.log('success', whatever_value_you_want_here);
  }