我是react.js的新手,我偶然发现了一个我无法解决的问题。我有一个较长的项目数组,要在两个不同的行中显示,这就是为什么我从该数组中取出大块并将它们添加到没有键和值的嵌套数组中的原因,如下所示:
constructor(props) {
super(props)
this.state = {
characters: [["Anakin","Darth Vader","Snoke"], ["Darth Maul", "Yoda", "Luke Skywalker"]],
}
}
在“字符”组件的渲染函数中,我使用了map函数,我想要的是将每个数组传递给组件“子数组”:
字符组件
render() {
return (
<div>
{this.state.characters.map((item, index )=> <Subarray key={index} title={item}></Subarray>)}
</div>
)
}
然后在“子数组”组件中,我要向该数组中的每个元素添加一个html元素:
子数组组件
export class Subarray extends Component {
render() {
return (
<div>
{this.props.title}
</div>
)
}
}
我无法获取要包装在div元素内的数组的每个元素:
输出:
<div><div>AnakinDarth VaderSnoke</div><div>Darth MaulYodaLuke Skywalker</div></div>
[您可以这样做,假设this.props.title
包含["Anakin","Darth Vader","Snoke"]
:
export class Subarray extends Component {
render() {
return (
<div>
{this.props.title.map((each, index) => <div key={index}>{each}</div>)}
</div>
)
}
}
我认为您必须将Subarray更改为类似的东西
export class Subarray extends Component {
render() {
return (
<div>
{this.props.title.map((item, index) => {
return <div key={index}>{item}</div>
})}
</div>
)
}
}
以这种方式,您遍历子数组中的每一项并呈现其中的每一项