在反应中将函数作为道具传递,无法读取未定义的 属性 '_handleEvent'
Pass function as a prop in react, Cannot read property '_handleEvent' of undefined
我尝试在 React 中实现 class table。 table 有多行,每行都有一个按钮。首先,我尝试传递一个函数 handleEvent。
现在,我总是以:
TypeError: 无法读取未定义的 属性 '_doDeleteItem'
存在某种绑定错误,但我无法解决。
干杯
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
里面的组件实例。使用箭头函数,绑定匿名函数,或将 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);
我尝试在 React 中实现 class table。 table 有多行,每行都有一个按钮。首先,我尝试传递一个函数 handleEvent。
现在,我总是以: TypeError: 无法读取未定义的 属性 '_doDeleteItem'
存在某种绑定错误,但我无法解决。
干杯
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
里面的组件实例。使用箭头函数,绑定匿名函数,或将 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);