javascript - 迭代数值并作为 Prop 发送

标签 javascript reactjs typescript

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

相关文章:

javascript - 从 ASP 代码隐藏调用外部 Javascript 函数

django - React.js 基于 DRF HTTP OPTIONS 动态生成表单

reactjs - 如何在 Typescript 中定义 React Navigation navigationOptions 参数

javascript - 等高不能正常工作?

javascript - 使用带有ajax和jquery的api调用初始化物化自动完成数据集

javascript - 组件已更新但没有视觉变化

reactjs - reducer 中存储的 ref 对象,没有 offsetTop 属性

javascript - NestJs 验证管道无法正常工作

angular - 如何获取和设置 primeNG 数据表中的当前页码?

javascript - 在迭代 jquery 对象时添加 html