我有一个带有值的数组,我使用forEach将值作为道具传递给组件。我还想发送一个值作为props,并在每次迭代时将其增加1。目前我已经尝试:

this.state = {
 index: 0
}
 let news:any[] = []; //container for other items for the loop
let indx = this.state.index;

    this.state.listItems.forEach((myArrWItems) => {

      indx = +1;
      news.push(<MyComponent


        index = {indx}

        />);
    });


但是,作为道具发送的值始终为1。有帮助吗?

最佳答案

您的index状态变量在那里不是必需的。由于要从现有阵列创建阵列,因此应使用map函数,如官方文档中所示。

此函数会将元素的index作为第二个参数直接带入其回调。

您的编码可以简化为一行:

const news = this.state.listItems.map((item, index) => <MyComponent key={index} index={index + 1}/>)


创建数组时,不要忘记设置组件的key属性。

<MyComponent index/>语法是<MyComponent index={index}/>的简短版本

关于javascript - 迭代数值并作为 Prop 发送,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55044183/

10-12 00:25
查看更多