我尝试在 React 中实现一个类表。一个表有多行,每行都有一个按钮。首先,我尝试传递一个函数 handleEvent。
现在,我总是以: 类型错误:无法读取未定义的属性“_doDeleteItem”
存在某种绑定(bind)错误,但我无法弄清楚。
干杯
class Table extends Component {
constructor(props,context) {
super(props,context);
this.state = { k : 3 };
this._handleEvent = this._handleEvent.bind(this);
}
_handleEvent (e) {
console.log('delete')
}
render() {
var rows = [];
var lastCategory = null;
this.props.results.slice(-this.state.k).forEach(function(r) {
rows.push( <Rows result = {r} deleteItem = {this._handleEvent} />);
});
return(
<Panel>
<ListGroup fill>
{rows}
</ListGroup>
</Panel>
);
}
}
export default Table;
class Rows extends Component{
render() {
return(
<ListGroupItem>
<b>Text:</b><Button onClick = {this.props.deleteItem} type="False"><b>True</b></Button><br/>
</ListGroupItem>
);
}
}
最佳答案
this
不是 forEach
中的组件实例.要么使用箭头函数,绑定(bind)匿名函数,要么将 this
作为第二个参数传递给 forEach
:
this.props.results.slice(-this.state.k).forEach(function(r) {
rows.push( <Rows result = {r} deleteItem = {this._handleEvent} />);
}.bind(this));
或
this.props.results.slice(-this.state.k).forEach(function(r) {
rows.push( <Rows result = {r} deleteItem = {this._handleEvent} />);
}, this);
关于javascript - 在 react 中将函数作为 Prop 传递,无法读取未定义的属性 '_handleEvent',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45275951/