首页 > 解决方案 > 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.

标签: javascriptreactjs

解决方案


包装一个匿名函数

<tr onClick={(event) => this.handleClick(event, arr)}>

然后你可以将当前的 arr 数据传递给手柄点击,我假设它负责设置弹出窗口。

状态管理解决方案

你可以发送一个 redux/context 动作 onClick 来设置currentActiveRow. 如果你 useSelector 或 useContext 钩子,那么你的模态总是可以默认读取它。


推荐阅读