繁体   English   中英

React.js如何从this.props数组中将index作为prop传递给子组件

[英]React.js how to pass in index as prop to child component from this.props array

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

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

<RankingCards {...this.props} tablePosition={this.props.indexOf(this)} />

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


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

{
    tableData: [
        {name: "John", index: 1},
        {name: "David", index: 2},
        {name: "Ardhya", index: 3}
    ]
}

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

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

在您的RankingCards组件中,您将获得除键之外的道具。

例如。 对于第一个实体,如果使用console.log(this.props)打印道具,则会以这种方式获取值。

{
    rawProp: {name: "John", index: 1},
    tablePosition: 1
}

this.props将引用Table组件的属性 - 但如果您的意思是将数组传递给Table组件,例如。 <Table personList={["John","Jeff","Joe"]} /> ,然后您可以在Table的渲染函数中使用for循环:

    render() {
      var rankingCards = []
      var personList = this.props.personList
      for (var i = 0; i < personList.length; i++) {
        rankingCards.push(<RankingCard {...personList[i].props} tablePosition={i} />)
      }
      return(
        <RankingCardContainer>
          {rankingCards}
        </RankingCardContainer>
      )
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM