首页 > 解决方案 > 如果每个单元格都是子组件,如何获取行索引?

问题描述

我目前正在尝试创建一个表,其中需要为每一行显示行索引。我认为这是一项简单的任务,但我很快意识到这超出了我的知识范围。


该表通过获取的 JSON 文件 (this.state) 进行迭代(映射),并通过React.createElement使用来自this.state.body.map()的道具“player”创建一个组件

下面是表格组件

render() {
        return (
            <div>
                <table className="ranked_table">
                    <tbody>
                    {this.state.body.map(player => React.createElement(Cell, player))}
                    </tbody>
                </table>
                <button id="vote_btn"><a>RANK</a></button>
            </div>
        );
    }

下面是行组件

render() {
        return (
            <tr className="row">
                <th>{**DESIRED RANK COLUMN**}</th>
                <th>
                    <div className="image_border">
                        <img src={this.props.image} className="profile_pic" alt="" >
                        </img>
                        <div className="medal"></div>
                    </div></th>
                <th><div className="name">{this.props.name}</div></th>
                <th>
                    <a className="upVote">
                        <img src="/asset/vote_btn.svg"></img>
                    </a>
                </th>
                <th className="count">{this.props.count}</th>
            </tr>
        );
    }

如何创建行索引列?我试图修改作为道具传递给行组件的状态对象,但我也被困在那里。

标签: javascripthtmlreactjshtml-table

解决方案


map函数将当前索引传递给它的回调函数。您可以将该索引传递给行组件

this.state.body.map((player, index) => React.createElement(Cell, {player, rowNum: index}))

index从零开始,您可能希望在将每个索引值作为道具传递时添加一个

React.createElement(Cell, {player, rowNum: index + 1 })

推荐阅读