React Component
export default class CommentBox extends React.Component {
constructor() {
super()
this.state ={
showComments: false,
comments: [
{ id: uuid.v4(), author: 'Clu', body: 'Just say no to love!', avatarUrl: 'images/default-avatar.png' },
{ id: uuid.v4(), author: 'Anne Droid', body: 'I wanna know what love is...', avatarUrl: 'images/default-avatar.png' }
]
}
}
render() {
const comments = this._getComments() || [];
let commentList;
if (this.state.showComments) {
commentList = <div className="comment-list">{comments}</div>
}
return(
<div className="comment-box">
<h3>COMMENTS</h3>
{this._getPopularMessage(comments.length)}
<h4 className="comment-count">{this._getCommentsTitle(comments.length)}</h4>
<button className="comment-toggle" onClick={this._toggleShowComments.bind(this)}>{this._toggleCommentButton()}</button>
<CommentForm addComment={this._addComment.bind(this)}/>
{commentList}
</div>
);
}
_addComment(author, body) {
const comment = {
id: uuid.v4(),
author: author,
body: body
}
this.setState({comments: this.state.comments.concat([comment])})
}
_getComments() {
return this.state.comments.map((comment) => {
return (<Comment
author={comment.author}
body={comment.body}
avatarUrl={comment.avatarUrl}
key={comment.id}
onDelete = {this._deleteComment.bind(this, null, comment.id)}/>)
});
}
主要问题...如果我省略event.stopPropagation
,当我运行它并单击"删除评论"链接时,一切都按预期工作。但是,当我添加它时,我得到错误Uncaught TypeError: Cannot read property 'stopPropagation' of null
.我假设 Comment 组件中的onClick
事件(请参阅底部代码框)没有传递事件。有什么办法可以纠正这一点吗?
_deleteComment(event, key) {
event.stopPropagation()
console.log(key)
this.setState (
{comments: this.state.comments.filter((singleComment) => singleComment.id !== key)
}
)
console.log(this.state.comments)
}
}
作为参考,注释组件:我尝试将(这个)绑定到onDelete
例如 <a className="comment-actions-delete" href="#" onClick={this.props.onDelete.bind(this)}>Delete comment</a>
但它似乎不起作用。
export default class Comment extends React.Component {
constructor() {
super();
this.state = {
isAbusive: false
};
}
render() {
let commentBody;
if (!this.state.isAbusive) {
commentBody = this.props.body;
} else {
commentBody = <em>Content marked as abusive</em>;
}
return(
<div className="comment">
<p className="comment-header">{this.props.author}</p>
<p className="comment-body">
{commentBody}
</p>
<div className="comment-actions">
<VotingButtons />
<a className="comment-actions-delete" href="#" onClick={this.props.onDelete}>Delete comment</a>
<a className="comment-actions-abuse" href="#" onClick={this._toggleAbuse.bind(this)}>Report as abuse</a>
</div>
</div>
);
}
_toggleAbuse(event) {
event.preventDefault();
this.setState({isAbusive: !this.state.isAbusive})
}
}
可能是你有错别字?
this.setState (
{coments: this.state.comments.filter((singleComment) => singleComment.id !== key)
}
与
commentList = <div className="comment-list">{comments}</div>
换句话说,您正在设置"coments",但正在检索"评论"。