反应组件
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)
}
}
供参考,评论组件:
我尝试将(this)绑定到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})
}
}
答案 0 :(得分:0)
可能是你有拼写错误?
this.setState (
{coments: this.state.comments.filter((singleComment) => singleComment.id !== key)
}
VS
commentList = <div className="comment-list">{comments}</div>
换句话说,您正在设置'coments'但检索'comments'。