javascript - 通过在 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);
});
}
解决方案
这似乎与 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 的交互,因此您可以专注于应用程序的业务逻辑。
推荐阅读
- django - Django 基于类的视图,一旦用户登陆页面,就将 request.session 设置为某个值
- java - 如何在List中使用excel数据
- c# - 在使用 EF Core 的通用存储库中包含使用反射的所有二级导航属性
- c# - 如何判断对象是放大还是缩小?
- html - 为什么我的弹性项目垂直溢出其父项?我怎样才能让弹性项目高度随父项缩小和增长?
- c - C中一维数组的元素在特定索引后不显示
- java - 如何将 JSON 从静态文件传递到休息控制器 SpringBoot App
- hibernate - 如何使用共享主键保存子实体
- scala - IntelliJ IDEA 无法找到 Artifactory 的凭据
- bixby - 如何定义提示的类别?