3
如何在該組件函數中獲取React組件狀態。這沒有與狀態相關的對象。我得到這個。狀態未定義在板removeComment
函數。基本上在董事會removeComment
函數我想刪除該索引的評論元素(作爲參數傳遞)。無法訪問事件處理程序函數中的`this.state`:ReactJS
class Board extends React.Component {
constructor(props) {
super(props);
this.state = {
comments:[
"One",
"Two",
"Three",
"four",
"five"
]};
};
removeComment(index) {
console.log('i was called',this.state);
}
render() {
console.log(this.state);
return (
<div className="board">
{
this.state.comments.map((text,i) => {
return (
<Comment key ={i} index = {i} commentText={text} removeComment={this.removeComment}/>
)
})
}
</div>
);
}
}
class Comment extends React.Component {
removeComment() {
var index = this.props.index;
this.props.removeComment(index);
}
render() {
return(
<div onClick={this.removeComment.bind(this)}>{this.props.commentText}</div>
);
}
}
感謝花花公子。你拯救了我的一天。 –
很高興,幫助你:) –