我正在尝试传递一个绑定函数(param)(有一个setState())作为属性,但是我遇到了这个错误,我实际上并不确定如何传递这种函数。
Cannot read property 'upadateComment' of undefined
这是我在index.js文件中的类片段(具有函数的类)
removeComment = (i) => {
console.log('removing comment: ' + i);
var arr = this.state.comments;
arr.splice(i, 1);
this.setState({comments: arr});
}
upadateComment = (newText , i) => {
console.log('updating comment: ' + i);
var arr = this.state.comments;
arr[i] = newText;
this.setState({comments: arr});
}
eachComment(text, i) {
return (
<Comment
key={i} index={i} updateCommentText={this.upadateComment}//here is the problem
removeCommentText={this.removeComment}> //and here
{text}
</Comment>
);
}
render() {
return (
<div>
{this.state.comments.map(this.eachComment)}
</div>
);
}
这是调用它们的地方(Comment.js文件)
edit = () => {
this.setState({editing: true});
}
remove = () => {
this.props.removeCommentText(this.props.index);
console.log('removing');
}
save = () => {
this.props.updateCommentText(this.refs.newText.value , this.props.index);
console.log('new Text: ');
this.setState({editing: false});
}
答案 0 :(得分:0)
由于eachComment
是函数声明,因此它引用了错误的this
上下文。我建议您将其更改为arrow function
。
eachComment = (text, i) => {
return (
<Comment
key={i} index={i} updateCommentText={this.upadateComment}
removeCommentText={this.removeComment}>
{text}
</Comment>
);
}