我正在 React JS 中渲染表格数据,但在单击子“删除”按钮时无法隐藏表格行。我当前的处理程序和渲染函数如下所示:
...
changeHandler: function(e) {
...
},
deleteHandler: function(e) {
e.currentTarget.closest("tr").style.visibility = "hidden";
},
render: function() {
return (
<div>
<div class="container">
<select onChange={ this.changeHandler.bind(this) }>
<option></option>
...
</select>
<table>
<thead>
<tr>
...
</tr>
</thead>
<tbody>
{data.map(function(row, j) {
return <tr key={j}>
<td>{row.text}</td>
<td><a href="" onClick={this.deleteHandler.bind(this, j)}>delete</a></td>
</tr>
}
)}
</tbody>
</table>
</div>
</div>
);
}
...
当我单击删除 anchor 时,我在控制台中收到此错误:
Uncaught TypeError: Cannot read property 'bind' of undefined
我不明白为什么我的删除处理程序没有被识别和绑定(bind),而我正在使用的 changeHandler
却被识别和绑定(bind)。有人可以告诉我如何让这个事件触发处理程序以及如何定位父 tr 将其隐藏吗?
最佳答案
更正上面的拼写错误后,我发现这不是这里的错误。查看以下 fiddle 以查看其实际效果。当您隐藏该行时,需要更改一些样式。
https://jsfiddle.net/vgo52rey/
问题出在 fiddle 过滤函数中“this”的绑定(bind)上。将其抽象为另一个方法,以便您可以将对 this 的引用存储在不同的变量中,然后您可以保留对 this.delete 或 this.deleteHandler 的引用。
delete: function(e) {
e.currentTarget.closest("tr").style.visibility = "hidden";
},
renderRows: function() {
var shouldIRender =(row) => (this.state.filter === row.status || this.state.filter === "");
var self = this
return requests.filter(shouldIRender).map(function(row, j) {
return <tr key={j}>
<td style={tdStyle}>{row.title}</td>
<td style={tdStyle}>{row.status}</td>
<td style={tdStyle}>{row.created_at}</td>
<td style={tdStyle}>{row.updated_at}</td>
<td style={tdStyle}><a href="#" onClick={self.delete}>delete</a></td>
</tr>
}
)
},
在你的渲染方法中,现在你可以只提供这个 renderRows 方法的返回值:
<tbody>
{this.renderRows()}
</tbody>
关于javascript - 在 React JS 中单击子 "delete"按钮时如何删除父表行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37199382/