我有一个带有值的数组,我使用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/