javascript - How to attach JSON data to an element to retrieve later in React?
问题描述
I have a TableComponent
which takes pulls data from API and tries to represent is inside a table. I'll write a minimal reproducible example.
My render method look like this:
const tableRows = this.renderTableRow();
return (
<table>
<thead>
<tr>
<th>Application Name</th>
<th>Total Valid Licenses</th>
<th>Current in Use</th>
</tr>
</thead>
<tbody>
{tableRows}
</tbody>
</table>
renderTableRow
is as follows, note that this.state.message
has all the data retrieved from the API (n number of objects which are about to be rendered as a table row):
return this.state.message.map(arr => // arr also has a key used_by which has a list of strings
<tr onClick={this.handleClick}>
<td>{arr.app_name}</td>
<td>{arr.valid_licenses}</td>
<td>{arr.inuse_licenses}</td>
</tr>
)
On handleClick
I want to show a modal with used_by
data for that row.
With Vanilla JavaScript I could have done it something like this:
let row = table.insertRow();
row.dataset.used_by = arr.used_by;
row.dataset.license_server = arr.license_server;
row.addEventListener("click", showModal);
And in showModal()
I can get used_by
by this.dataset.used_by
.
解决方案
包装一个匿名函数
<tr onClick={(event) => this.handleClick(event, arr)}>
然后你可以将当前的 arr 数据传递给手柄点击,我假设它负责设置弹出窗口。
状态管理解决方案
你可以发送一个 redux/context 动作 onClick 来设置currentActiveRow
. 如果你 useSelector 或 useContext 钩子,那么你的模态总是可以默认读取它。
推荐阅读
- javascript - 从 ReactJS 中的 API 获取数据后如何重新渲染前端
- c - cs50 恢复,恢复的图像不匹配
- reactjs - 延迟加载 ReactJS 组件
- amazon-web-services - AWS IoT Core 中是否有任何规定可以获取以前的影子状态?是否有任何 API / 配置历史?
- sql - 每天都有窗口函数的 SQL 性能问题
- python - 正则表达式从python中的文本中识别固定字符字母数字词
- c - 如何在 C 项目中获取状态进程?
- git - 如何仅提交与现有 github 远程存储库不同的文件?
- python - 单线制造轮子失败
- python - Skimage.io.read 读取一个 PIL 对象