javascript - 如果每个单元格都是子组件,如何获取行索引?
问题描述
我目前正在尝试创建一个表,其中需要为每一行显示行索引。我认为这是一项简单的任务,但我很快意识到这超出了我的知识范围。
该表通过获取的 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>
);
}
如何创建行索引列?我试图修改作为道具传递给行组件的状态对象,但我也被困在那里。
解决方案
map
函数将当前索引传递给它的回调函数。您可以将该索引传递给行组件
this.state.body.map((player, index) => React.createElement(Cell, {player, rowNum: index}))
index
从零开始,您可能希望在将每个索引值作为道具传递时添加一个
React.createElement(Cell, {player, rowNum: index + 1 })
推荐阅读
- python-3.x - Pyautogui如何单击单选按钮
- sql-server - SSIS:执行 SQL 任务与数据流任务
- swiftui - 需要确认在 iOS14 中被双重加载的视图
- jmeter - 非 GUI 模式下 Jmeter 测试后生成 .jtl(用于分析)和 .csv(用于报告)文件
- c# - Umbraco 8 模型生成器无法找到 doctype 生成的文件
- python - 如何使用击键将 python 复制并粘贴到某个应用程序中?
- java - Ebean RawSql 不允许在“case when”子句中使用命名参数
- java - Androd Studio 在特定时间安排一个方法
- matlab - 节点排序的空间填充曲线
- bootstrap-4 - 我可以让 Bootstrap 宽度响应吗