gpt4 book ai didi

javascript - 绑定(bind)函数作为属性传递 React

转载 作者:行者123 更新时间:2023-11-28 02:35:46 24 4
gpt4 key购买 nike

我试图传递一个绑定(bind)函数(参数)(有一个 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});
}

最佳答案

由于 eachComment 是一个函数声明,它引用了错误的 this 上下文。我建议您将其更改为 arrow function

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

关于javascript - 绑定(bind)函数作为属性传递 React,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47490501/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com