React.js 如何将索引作为道具从 this.props 数组传递给子组件

ugo*_*chi 5 javascript arrays this reactjs

React 新手,如果我的术语偏离目标,请提前道歉。我有一张桌子,上面列出了按特定顺序排列的人员名单。我需要能够this.props.tablePosition根据有关人员的索引创建一个值。

this.props是 Table 组件中的一个数组。我有下面的代码不起作用,因为我不确定如何获取索引。

<RankingCards {...this.props} tablePosition={this.props.indexOf(this)} />
Run Code Online (Sandbox Code Playgroud)

abh*_*ake 2

需要查看其余的代码,但根据我的理解,你需要这种流程,但如果我错了,请纠正我;)


如果您在父组件中获得这样的道具

{
    tableData: [
        {name: "John", index: 1},
        {name: "David", index: 2},
        {name: "Ardhya", index: 3}
    ]
}
Run Code Online (Sandbox Code Playgroud)

您可以像这样向各个子组件提供所需的数据。

this.props.tableData.map(function(data){
    // do whatever processing you want to perform
    return(
        <RankingCards rawProp={data} tablePosition={data.index} key={data.index} />
    )
})
Run Code Online (Sandbox Code Playgroud)

在 RankingCards 组件中,您将获得除 key 之外的 props。

例如。对于第一个实体,如果您使用 打印 props console.log(this.props),您将以这种方式获得值。

{
    rawProp: {name: "John", index: 1},
    tablePosition: 1
}
Run Code Online (Sandbox Code Playgroud)