错误:预期 onClick 侦听器是一个函数,而是使用 reactjs 获取类型对象



我正在使用onClick函数并尝试传递一个对象。我需要对象来使函数工作。但是由于某种原因,它给了我这个错误。

该错误来自我在每条评论上呈现的删除按钮中的 onClick 函数。如果我删除我随它一起传递的评论,错误就会消失(因此函数本身不是问题(。我不确定我是否通过错误或什么传递评论。

就像我通常做的那样,如果您要求更多信息或希望我尝试控制台日志某些内容,我会将其放在编辑中,这样评论就不会变得拥挤,并且其他人更容易看到。

renderCommentsButtons(comment) {
const { post, user, auth } = this.props;
if(!user) {
return (<div></div>);
}
if(auth) {
if(user._id === comment.author.id) {
return (
<div>
<button
onClick={this.deleteComment, comment}
className="btn btn-xs btn-danger">
Delete
</button>
<Link
to={`/posts/${post._id}/comments/${comment._id}/edit`}
className="btn btn-xs btn-warning">
Edit
</Link>
</div>
)
}
}
}
renderComments() {
const { post } = this.props;
return post.comments.map((comment) => {
return (
<li className="list-group-item" key={comment._id}>
<div>
{comment.text} : {comment.author.email}
</div>
{this.renderCommentsButtons(comment)}
</li>
);
});
}
deleteComment({ author, _id}) {
const {id} = this.props.match.params;
const {user} = this.props;
if(this.props.auth) {
if(user._id === author.id){
this.props.deleteComments(id, _id, () => {
this.props.history.push(`/posts/${id}`);
});
}
}
}

试试这个:

<button
onClick={() => this.deleteComment(comment)}
className="btn btn-xs btn-danger">
Delete
</button>

您没有正确传递注释,onClick只接受一个函数,如果要传递参数,则必须像上面一样执行。

最新更新