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



如何通过 innerHTML 在 react class 中添加 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 无关,但是,您通常会在定义innerHTML的情况下单独添加 onclick 函数。如果这是您要走的路线,我建议您倾向于 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 的交互,因此您可以专注于应用程序的业务逻辑。

react是完全不同的事情,你不能在纯 HTML 中添加 react 。

最新更新