如何使用React.js渲染嵌套数组?

问题描述 投票:0回答:2

我是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>
arrays reactjs nested render chunks
2个回答
2
投票

[您可以这样做,假设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>
        )
    }
}

1
投票

我认为您必须将Subarray更改为类似的东西

export class Subarray extends Component {
    render() {
        return (
            <div>
               {this.props.title.map((item, index) => {
                  return <div key={index}>{item}</div>
               })}
            </div>
        )
    }
}

以这种方式,您遍历子数组中的每一项并呈现其中的每一项

© www.soinside.com 2019 - 2024. All rights reserved.