单击时发送 row/cell 数据到函数 - ReactJS
Sending row/cell data on click to the function - ReactJS
我正在从 componentWillMount 中检索 table 数据并将其显示为 UI。我想在单击 row/cell 时触发一个功能,并且 return 该值返回到另一个 PHP 以便我可以使用检索到的单元格值查询后端。
- index = 0,1,2,3(我有 4 列)
- 行 = 每个索引的数据。
我不确定为什么 this.state.testTime 没有向 handleClick 函数发送正确的值。有人对此有任何意见吗?谢谢
_handleClick: function (event) {
this.setState({testTime: event.target.value});
console.log(event.target.value);
var data = {
testTime: this.state.testTime
}
console.log("clicked");
$.ajax({
type: "GET",
crossDomain: true,
url: "http://localhost:8080/TEST/capture.php",
data: data,
success: function(data){
alert(data);
},
error:function(data)
{
alert("Data sending failed");
}
});
},
return (
<tbody>
{tableData.map((row, index) => {
return (
<tr key={"row_" + index} >
{row.map((cell, index) => {
return (
<td key={"cell_" + index} onClick={this._handleClick} value={this.state.testTime} >{cell}</td>
);
})}
</tr>
);
})}
</tbody>
)
setState
是一个异步函数,它接受一个回调作为第二个参数,一旦 setState
完成并且组件被重新渲染,它就会被执行。因此,您需要直接对 data
变量使用 event.target.value
或将您的代码放入回调中:
this.setState({testTime: event.target.value} ,() => {
var data = {testTime: this.state.testTime}
...
$.ajax...
});
我正在从 componentWillMount 中检索 table 数据并将其显示为 UI。我想在单击 row/cell 时触发一个功能,并且 return 该值返回到另一个 PHP 以便我可以使用检索到的单元格值查询后端。
- index = 0,1,2,3(我有 4 列)
- 行 = 每个索引的数据。
我不确定为什么 this.state.testTime 没有向 handleClick 函数发送正确的值。有人对此有任何意见吗?谢谢
_handleClick: function (event) {
this.setState({testTime: event.target.value});
console.log(event.target.value);
var data = {
testTime: this.state.testTime
}
console.log("clicked");
$.ajax({
type: "GET",
crossDomain: true,
url: "http://localhost:8080/TEST/capture.php",
data: data,
success: function(data){
alert(data);
},
error:function(data)
{
alert("Data sending failed");
}
});
},
return (
<tbody>
{tableData.map((row, index) => {
return (
<tr key={"row_" + index} >
{row.map((cell, index) => {
return (
<td key={"cell_" + index} onClick={this._handleClick} value={this.state.testTime} >{cell}</td>
);
})}
</tr>
);
})}
</tbody>
)
setState
是一个异步函数,它接受一个回调作为第二个参数,一旦 setState
完成并且组件被重新渲染,它就会被执行。因此,您需要直接对 data
变量使用 event.target.value
或将您的代码放入回调中:
this.setState({testTime: event.target.value} ,() => {
var data = {testTime: this.state.testTime}
...
$.ajax...
});