我正在玩纸牌游戏。我有这个json db:
{
"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"
}
]
}
我有这个父组件,它获取json数据以传递给子组件。数据已成功获取。
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">
{console.log(this.state.characters)}
<Player data={this.state.characters}/>
<Player data={this.state.characters}/>
</div>
)
}
}
export default Stage
现在,我要在动态<li>
中为该组件内的每个字符呈现每个卡片。例如,我有3个字符,所以我要渲染3张卡片。每个匹配一个字符。我该怎么做?我想将<Card>
组件的属性传递给
import React from 'react'
import Card from './Card'
const Player = (props) => {
return (
<div className="player">
<Card/>
</div>
)
}
export default Player
答案 0 :(得分:2)
为此,您要使用.map()
。基本上,您需要一个数组,然后从该数组返回一组反应组件。例如:
const Player = ({ data }) => {
return (
<div className="player">
{data.map((character, i) => (
<Card key={i} name{character.name}/>
))}
</div>
)
}
在这里,我已经将name
密钥向下传递到每张卡中,但是您可以传递任何您想要的内容(如果有必要的话,包括整个character
对象)。
此外,我将data
重命名为characters
,因为这样做更有意义。而且我会将prop的默认值设置为一个空数组。
答案 1 :(得分:1)
只需使用.map()函数即可循环访问数组的每个项目。
.map()
{data.map((item, i) => (
<Card key={i} name={item.name}/>
))}