ReactJs Onclick Not Working If Append To Table in Javascript



我通过数组将JsonArray数据推送到reactjs中的数据表,如下所示。

tableTest= () => { //Function Name
axios({
method: 'post',
url: "/test" //URL
})
.then(response => {
var testArray= [];
var slNo = 0;
response.data.map((item, index) => {
var result = [];
slNo++;
var result = [];
result.push(slNo);
result.push(item.id);
result.push(item.name);
result.push(item.mob);
result.push("<button onclick={this.accept}>Accept</button>");
testArray.push(result);
})
this.setState({ testTableTable: testArray});
}).catch(response => {
console.log("Error", response);
})
}

如果我点击接受按钮,我会得到"this.Accept"不是一个函数。

有人能告诉我如何用Javascript编写onclick函数吗。

谢谢:(

使用数据表的onclick列函数代替onclick函数,源代码如下所示:

tableTest= () => { 
axios({
method: 'post',
url: "/test" //URL
})
.then(response => {
var testArray= [];
var slNo = 0;
response.data.map((item, index) => {
var result = [];
slNo++;
var result = [];
result.push(slNo);
result.push(item.id);
result.push(item.name);
result.push(item.mob);
result.push("<button class='accept"+index+"'>Accept</button>");//define class here to use reference for column onClick function
testArray.push(result);
})
this.setState({ testTableTable: testArray});
}).catch(response => {
console.log("Error", response);
})
}

//将表格更改为Datatable

setDataTableData = () => { //set datatable
this.$el2 = $(this.el2) //el2 is reference of table
this.$el2.DataTable(
{
data: this.state.RowTableData, //RowTableData is array
"columnDefs": [
//column click function goes here
{
"targets": 4,// 4th column in a table
"createdCell": (td, cellData, rowData, row, col) => {
$(td).on('click', '.accept' + row, () => { //Click on <td>
this.accept(); //call function here
})
}
}
],
}
)
}

//此处接受功能

accept =() =>{
//function here
}
.then(response => {
var testArray= [];
window.YOUR_CLICK_FN = this.accept.bind(this);
var slNo = 0;
response.data.map((item, index) => {
var result = [];
slNo++;
var result = [];
result.push(slNo);
result.push(item.id);
result.push(item.name);
result.push(item.mob);
result.push("<button onclick={YOUR_CLICK_FN}>Accept</button>");
testArray.push(result);
})
this.setState({ testTableTable: testArray});
}).catch(response => {
console.log("Error", response);
})

问题在于重新绑定。

React事件处理程序使用camelCase命名。您应该调用onClick而不是onclick

请参阅以下链接:https://reactjs.org/docs/handling-events.html

CodeSandbox示例:https://codesandbox.io/s/3rp301jjym

tableTest= () => { //Function Name
axios({
method: 'post',
url: "/test" //URL
})
.then(response => {
var testArray= [];
var slNo = 0;
response.data.map((item, index) => {
var result = [];
slNo++;
var result = [];
result.push(slNo);
result.push(item.id);
result.push(item.name);
result.push(item.mob);
result.push((<button onclick={this.accept}>Accept</button>));
testArray.push(result);
})
this.setState({ testTableTable: testArray});
}).catch(response => {
console.log("Error", response);
})
}

问题是它被存储为字符串。所以你必须把它作为一个反应组件来推动它工作。

onclick在react中不起作用。你必须使用onClick

最新更新