我開始嘗試學習反應,並遇到了一個我似乎無法解決的問題。通過教程去製作一個簡單的評論編輯的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方法。 –