我有一个包含值的数组,我使用 forEach 将值作为 props 传递给组件。我还想发送一个值作为 Prop ,并在每次迭代时将其增加 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}
/>);
});
但是,作为 props 发送的值始终为 1。有什么帮助吗?
最佳答案
你的 index
那里不需要状态变量。因为你想从一个现有的数组创建一个数组,你应该使用 map
功能,如官方文档所示。
这个函数会给你 index
将您的元素作为第二个参数直接放入其回调中。
您的代码可以减少到一行:
const news = this.state.listItems.map((item, index) => <MyComponent key={index} index={index + 1}/>)
不要忘记设置 key
制作数组时组件的 Prop 。
<罢工><MyComponent index/>
syntax 是 <MyComponent index={index}/>
的缩写版本罢工>
关于javascript - 迭代数值并作为 Prop 发送,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55044183/