【问题标题】:How to pass a field of datasource as parameter of onclick function in a table row using ant and ReactJs?如何使用ant和ReactJs在表格行中将数据源字段作为onclick函数的参数传递?
【发布时间】:2023-04-08 02:35:01
【问题描述】:
我正在使用 ant 和 ReactJs 处理一个项目并遇到如下问题:我的数据源是一个对象数组,其中包含一些字段,例如 id、photoUrl、name、phone 和 email。我使用这个数据源创建了一个表,其中包含头像、姓名、电话号码、电子邮件和操作列。 Action是一个链接文本编辑,还有一个onClick功能,用来编辑表格行的信息。
现在我想将每一行中数据的 id 传递给编辑 onClick 函数的参数。到目前为止,我尝试将列 Action 的 dataIndex 设置为“id”,并将 id 作为参数传递给 onClick 函数,如下面的代码,但它只是挂断了屏幕。
{
title: 'Action',
dataIndex: 'id',
key: 'id',
render: (id) => (
<span>
<a href="javascript:;" onClick={this.handleEditBtnClick(id)}>
Edit
</a>
</span>
),
},
这是我的数据对象的一个例子
{
"id": 21,
"photoUrl": "https://dummyimage.com/600x400/d11b1b/ffffff&text=patient+21",
"displayName": "patient 21",
"phone": "0901993159",
"email": "pp21@yopmail.com"
},
感谢您的宝贵时间。
【问题讨论】:
标签:
reactjs
antd
tablerow
【解决方案1】:
你在onClick上绑定handleEditBtnClick函数的方式是错误的
应该是:onClick={() => {this.handleEditBtnClick(id)}}
当前的实现是在每次渲染时触发 handleEditBtnClick 函数调用,而不是将函数与 onClick 绑定。然后你的渲染进入无限循环并且你的屏幕挂起。
{
title: 'Action',
dataIndex: 'id',
key: 'id',
render: (id) => (
<span>
<a href="javascript:;" onClick={() => {this.handleEditBtnClick(id)}}>
Edit
</a>
</span>
),
},
你也可以参考这个solution 进一步解释这个问题
希望对您有所帮助。恢复任何混淆。
【解决方案2】:
改变这个:
<a href="javascript:;" onClick={this.handleEditBtnClick(id)}>
Edit
</a>
收件人:
<a href="javascript:;" onClick={() => this.handleEditBtnClick(id)}>
Edit
</a>
【解决方案3】:
如果您只想编辑该行,您也可以使用如下状态对其进行管理:
{
title: 'Action',
dataIndex: 'id',
key: 'id',
render: (id) => (
<span>
<a href="javascript:;" onClick={() => {this.setState({selected: id})}}>
Edit
</a>
</span>
),
},