首页 > 解决方案 > 通过在 react 类中通过 innerHTML 添加 onclick 事件来调用函数

问题描述

如何通过innerHTML在react类中添加onclick事件来调用函数

document.getElementById('activeEmployeesTableContent').innerHTML = `
                                    <tr>
                                      <td>${res.data.empId}</td>
                                      <td><button onclick = ${this.fun}>CLICK</button></td>
                                    </tr>
                                  `;

上面的代码不起作用,但我必须使用 innerHTML 将代码动态添加到表体中

  componentDidMount(){
     axios.post('http://localhost:5000/employeesRetrieval')
      .then( res => {
          document.getElementById('activeEmployeesTableContent').innerHTML = `
                                  <tr>
                                    <td>${res.data.empId}</td>
                                    <td><button onclick = ${this.fun(res.data.empid)}>CLICK</button></td>
                                  </tr>`;
      }).catch( err => {
        console.log(err);
      });
  }

标签: javascriptreactjsonclickinnerhtml

解决方案


这似乎与 React 相切,但是,您通常会添加 onclick 函数,而不是定义innerHTML. 如果这是您尝试走的路线,我建议您使用 DOM api。

const t = document.getElementById('table');
const row = document.createElement('tr');
const id = document.createElement('td');

// Set up the first element in the table
id.innerHTML = ele.empId;
row.appendChild(id);

// Set up the button
const btn = document.createElement('button');
btn.innerHTML = 'CLICK';
btn.addEventListener('click', func);
row.appendChild(btn);

// Add the row to the table.
table.appendChild(row);

这种方法过于必要,而且通常缺乏框架,所以我不建议做这样的事情。存在像 React 这样的框架来帮助管理复杂性。React 为您处理与 DOM 的交互,因此您可以专注于应用程序的业务逻辑。


推荐阅读