我是React的新手,我正在尝试使用React.js在帖子上创建一个upvote功能。我有post_list_item.js.jsx
:
var PostListItem = React.createClass({
render: function() {
return (
<div className="post">
<div className="post-upvote"><button type="button" class="btn btn-primary">Upvote</button></div>
<div className="post-body">
<h3>
<a href={this.props.post.title} target="_blank">{this.props.post.title}</a>
</h3>
<p>{this.props.post.content}</p>
</div>
<div className="post-controls">
<div className="post-control">
<div className="user-badge-container ">
<img src={this.props.post.user.picture_url} className="avatar"/>
</div>
</div>
</div>
</div>
);
}
});
和upvote.js.jsx
:
var Upvote = React.createClass({
getInitialState: function() {
return {
post: this.props.post
}
},
render: function() {
var divClasses = classNames({
"post-upvote": true,
"post-upvote-upvoted": this.state.post.up_voted
});
return (
<div className={divClasses} onClick={this.handleClick}>
<div className="post-upvote-arrow"></div>
<div className="post-upvote-count">
{this.state.post.up_votes}
</div>
</div>
);
}
});
我的帖子列表会在每个帖子旁边显示一个upvote按钮。但是,当我点击upvote按钮时没有任何反应。
这是我添加到application.js文件中的handleClick()函数:
var handleClick = function() {
var that = this;
$.ajax({
type: 'POST',
url: Routes.upvote_post_path(this.props.post.id, { format: 'json' }),
success: function(data) {
that.setState({ post: data });
}
});
}
我错过了什么吗?
答案 0 :(得分:1)
当你说{this.handleClick}
(在你的反应组件中)时,它意味着“使用在这个组件上定义的handleClick函数”。
该函数应该与var Upvote = react.createClass
中的其他函数一致(它应该是一个实例方法,基本上)。
答案 1 :(得分:1)
在Upvote
组件中没有方法handleClick
,因此您转到onClick
undefined
。,将handleClick
方法移至Upvote
< / p>
var Upvote = React.createClass({
getInitialState: function() {
return {
post: this.props.post
}
},
handleClick: function() {
var that = this;
$.ajax({
type: 'POST',
url: Routes.upvote_post_path(this.props.post.id, { format: 'json' }),
success: function(data) {
that.setState({ post: data });
}
});
},
render: function() {
var divClasses = classNames({
"post-upvote": true,
"post-upvote-upvoted": this.state.post.up_voted
});
return (
<div className={divClasses} onClick={this.handleClick}>
<div className="post-upvote-arrow"></div>
<div className="post-upvote-count">
{this.state.post.up_votes}
</div>
</div>
);
}
});