我开始尝试学习反应,并遇到了一个我似乎无法解决的问题。通过教程去制作一个简单的评论编辑的Web应用程序,当我尝试更新的评论我得到这个错误“类型错误:_this3未定义”,特别是在这些线路上:React.js TypeError this.props未定义
this.props.updateCommentText(this.refs.newText.value, this.props.index);
这一个:
updateCommentText={()=>this.updateComment}
以下是完整的javascript代码:
class Comment extends React.Component{
constructor(){
super();
this.state = {
editing: false,
};
this.edit = this.edit.bind(this);
this.save = this.save.bind(this);
}
edit(){
this.setState({
editing: true,
});
}
save(){
this.props.updateCommentText(this.refs.newText.value, this.props.index);
this.setState({
editing: false,
});
}
remove(){
console.log('Removing comment');
this.props.deleteFromBoard(this.props.index)
}
renderNormal(){
return (
<div className="commentContainer">
<div className="commentText">{this.props.children}</div>
<button onClick={this.edit} className="button-primary">Edit</button>
<button onClick={this.remove} className="button-danger">Remove</button>
</div>
);
}
renderForm(){
return (
<div className="commentContainer">
<textarea ref="newText" defaultValue={this.props.children}></textarea>
<button onClick={this.save} className="button-success">Save</button>
</div>
);
}
render(){
if(this.state.editing){
return this.renderForm();
} else {
return this.renderNormal();
}
}
}
class Board extends React.Component{
constructor(){
super();
this.state = {
comments: [
"Hiya",
"Awk well",
"Boo-urns"
],
}
}
removeComment(i){
console.log("Removing comment: " + i);
var arr = this.state.comments;
arr.splice(i, 1);
this.setState({
comments: arr
});
}
updateComment(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.updateComment}
deleteFromBoard={()=>this.removeComment}>
{text}
</Comment>
);
}
render(){
return (
<div className="board">
{
this.state.comments.map(this.eachComment)
}
</div>
);
}
}
// ========================================
ReactDOM.render(
<Board />,
document.getElementById('container')
);
我假设的东西已经出去的范围,但我不知道在哪里。
的可能的复制[类型错误:无法读取属性<功能\ _name>的不确定结合的onClick时] (https://stackoverflow.com/questions/43568344/typeerror-cannot-read-property-function-name-of-undefined-when-binding-onclic) –
你传递一个组件与'ref =“newText”'为你的容器里有一个孩子,你在这里描述过吗? 请参阅:https://stackoverflow.com/questions/34678340/react-how-to-access-refs-in-this-props-children –
更改** 1。**:绑定上下文以使用此内部映射body,this.state.comments.map(this.eachComment,this)** 2。**传递参数'updateCommentText = {(a,b)=> this.updateComment(a,b)} deleteFromBoard = {(a,b)=> this.removeComment(a,b)} ** ** 3.在构造函数中绑定remove方法。 –