gpt4 book ai didi

javascript - ReactJs - 以更高级的方式将 Prop 传递给子组件

转载 作者:行者123 更新时间:2023-12-01 01:13:08 24 4
gpt4 key购买 nike

我正在制作一个纸牌游戏,我有这个 db.json:

{
"characters": [
{
"name": "Character1",
"punch":12,
"kick":12,
"special":15,
"image":"character1"

},
{
"name": "Character2",
"punch":13,
"kick":11,
"special":15,
"image":"character2"
},

{
"name": "Character3",
"punch":20,
"kick":19,
"special":10,
"image":"character3"
},
{
"name": "Character4",
"punch":21,
"kick":18,
"special":2,
"image":"character4"
}
]
}

所以我有这个父组件将数据获取到子组件:

import React, { Component } from 'react'
import Player from './Player'

var data = require('./db.json');

class Stage extends Component {
constructor(props) {
super(props)
this.state = {
characters: []
}
}

componentDidMount() {
this.setState({
characters: data.characters
})
}

render() {
return (

<div className="stage">
<Player data={this.state.characters}/>
<Player data={this.state.characters}/>
</div>
)
}
}


export default Stage

每个<Player>组件正在接收相同的数据。我想分发为每个组件划分的数据。例如,我有 4 个字符,每个组件可能会随机接收 2 个字符。举个更清楚的例子:

玩家1: Angular 色1, Angular 色2或字符2、字符4或字符3、字符2等...

玩家 2 也是如此

每个玩家可能没有重复的 Angular 色。怎么解决?

这是一个<Player>组件代码

import React from 'react'
import Card from './Card'

const Player = ({data}) => {
return (
<div className="player">
{data.map(character => (
<Card name={character.name}/>
))}
</div>
)
}

export default Player

最佳答案

您只需添加一个名为player1和player2的新状态,创建一个新数组并将其传递给相应的组件即可完成此操作。

class Stage extends Component {
constructor(props) {
super(props)
this.state = {
player1: [],
player2: [],
}
}

componentDidMount() {
const shuffled = data.characters.sort(() => 0.5 - Math.random());
const player1 = shuffled.slice(0, 2);
const player2 = shuffled.slice(2,4);
this.setState({
player1,
player2,
})
}

render() {
return (
<div className="stage">
<Player data={this.state.player1}/>
<Player data={this.state.player2}/>
</div>
)
}
}

关于javascript - ReactJs - 以更高级的方式将 Prop 传递给子组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54996125/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com