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

How do I render a nested Array with React.js?

我是 react.js 的新手,我偶然发现了一个我无法理解的主题。我有一长串项目,我想在两个不同的行中显示,这就是为什么我从这个数组中取出块并将它们添加到没有键和值的嵌套数组中,如下所示:

constructor(props) {
        super(props)
        this.state = {
            characters: [["Anakin","Darth Vader","Snoke"], ["Darth Maul", "Yoda", "Luke Skywalker"]],
        }
    }

在 "Characters" 组件的渲染函数中,我使用了 map 函数,我想要的是将每个数组传递给组件 "Subarray":

字符组件

 render() {
        return (
            <div>
                {this.state.characters.map((item, index )=> <Subarray key={index} title={item}></Subarray>)}
            </div>
        )
    }

然后在 "Subarray" 组件中,我想向该数组中的每个元素添加一个 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>

我认为您必须将子阵列更改为类似

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