【问题标题】:How do I render a nested Array with React.js?如何使用 React.js 渲染嵌套数组?
【发布时间】:2020-05-14 21:33:22
【问题描述】:

我是 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>
        )
    }

然后在“子数组”组件中,我想为该数组中的每个元素添加一个 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.state.characters 是你的整个var array 吗?
  • 什么是character
  • 输出显示如下:&lt;div&gt;&lt;div&gt;AnakinDarth VaderSnoke&lt;/div&gt;&lt;div&gt;Darth MaulYodaLuke Skywalker&lt;/div&gt;&lt;/div&gt;。它们不会被包裹在 html 元素中
  • 是的,this.state.characters 是我的全部 var array

标签: arrays reactjs nested render chunks


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

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

    这样你循环遍历子数组中的每一项并渲染它们中的每一项

    【讨论】:

      猜你喜欢
      • 2021-07-21
      • 1970-01-01
      • 2019-05-12
      • 1970-01-01
      • 2018-08-12
      • 2020-08-01
      • 1970-01-01
      • 2023-01-18
      • 1970-01-01
      相关资源
      最近更新 更多