绑定函数随着属性反应而传递



我正在尝试传递绑定函数(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 file)

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});
}

由于 eachComment是函数声明,因此是指错误的 this上下文。我建议您将其更改为arrow function

eachComment = (text, i) => {
    return (
        <Comment                            
        key={i} index={i} updateCommentText={this.upadateComment}
        removeCommentText={this.removeComment}>
        {text}
        </Comment>
    );
}

最新更新