【问题标题】:Reactjs add onClick attribute on a dynamic elementReactjs 在动态元素上添加 onClick 属性
【发布时间】:2021-11-08 14:38:56
【问题描述】:

我试图根据从反应应用程序中的 ajax 响应接收到的数据动态创建一个表。该循环是根据 useEffect 钩子内的 ajax 请求的响应创建的。问题是我无法使表格单元格中锚标记中的 onClick 属性起作用。下面是代码。

res.data.users.forEach(function (user) {
          let row = table.insertRow(rowcnt);
          let cell1 = row.insertCell(0);
          let cell2 = row.insertCell(1);
          let cell3 = row.insertCell(2);
          cell1.innerHTML = user.u_id;
          cell2.innerHTML = user.username;
          cell3.innerHTML = '<a href="javascript:void(0)"><span data-feather="edit"></span></a><a href="javascript:void(0)" onClick={(e) => deleteUser(e, ' + user.id + ')}><span data-feather="trash"></span></a>';
          rowcnt++;
        });

但在前端显示

请帮忙。

【问题讨论】:

  • 您应该使用createElementappendChild 而不是innerHTML = "element string" 以获得更易读的代码。您的 onClick 也令人困惑,您想用它做什么?
  • 我认为你应该不使用 react ,也许将给定的数据设置在一个状态中会更好,并根据它构建你的表......不?
  • @Jesper 调用 axios.delete 删除用户。
  • @BENARDPatrick 是的,我是 react 新手

标签: javascript reactjs


【解决方案1】:

“React 方式”是使用:

  1. state 维护数据。

  2. map 遍历状态中保存的用户数据并为每个用户生成 HTML 数组。为每个 tr 元素添加一个 id。

  3. filterdeleteUser 函数中过滤掉u_ids 与已删除行的id 不匹配的行数据,并使用该数组来更新组件将在该点重新的状态使用更新后的状态进行渲染。

const { useState } = React;

function Example({ data }) {

  const [ users, setUsers ] = useState(data.users);

  function deleteUser(id) {
    // Call Axios with the id to delete that item
    const filtered = users.filter(user => user.u_id !== id);
    setUsers(filtered);
  }

  function getRows(users) {
    return users.map(user  => {
      const { u_id, username } = user;
      return (
        <tr key={u_id} id={u_id}>
          <td>{u_id}</td>
          <td>{username}</td>
          <td class="delete">
            <a onClick={() => deleteUser(u_id)}>Delete</a>
          </td>
        </tr>
      )
    });
  }

  return (
    <table>
     {getRows(users)}
    </table>
  );
};

const data = {
  users: [
    {u_id: 1, username: 'Steve'},
    {u_id: 2, username: 'Polly'},
    {u_id: 3, username: 'Brian'},
    {u_id: 4, username: 'Billy Joel'}
  ]
};

ReactDOM.render(
  <Example data={data} />,
  document.getElementById("react")
);
.delete { background-color: red; cursor:pointer; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
<div id="react"></div>

【讨论】:

  • 在删除函数中我需要调用 axios 并从数据库中删除数据,然后刷新表。
  • 我只能提供一个小例子来说明你应该如何解决这个问题。您的问题中没有提到 Axios,但是在该函数中使用行 ID 调用 Axios 应该非常简单。
  • 但是用户数据也是从 axios 调用中获取的。那么useState有什么用呢?
  • 因为这就是 React 处理数据的方式。状态更新,然后组件更新。
  • 但我不能在 axios 中使用useState。我收到错误React Hook "useState" cannot be called inside a callback. React Hooks must be called in a React function component or a custom React Hook function react-hooks/rules-of-hooks
【解决方案2】:

我认为你应该使用jsx 来代替innerHTML,像这样:

return (
  <table>
    <thead>
      <tr>
        <th>u_id</th>
        <th>usename</th>
        <th>action</th>
      </tr>
    </thead>
    <tbody>
      {res.data.users.map(user => (
        <tr>
          <td>{user.u_id}</td>
          <td>{user.username}</td>
          <td>
            <a onClick={(e) => deleteUser(e, ' + user.id + ')}>delete</a>
          </td>
        </tr>
      )}
    </tbody>
  </table>
)

【讨论】:

  • 循环是根据 useEffect 钩子内的 ajax 请求的响应创建的。
  • 桌子已经在那里了。我只是在创建行。
猜你喜欢
  • 2018-08-05
  • 1970-01-01
  • 2019-06-24
  • 2014-02-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-06
  • 2019-11-13
相关资源
最近更新 更多