我正在尝试使用handleClick()函数实现3件事。将buttonText切换为跟随或跟随,切换'active'类并处理FOLLOW操作。我可能做得不对。出于某种原因,onClick事件对此任何事件都没有影响。有任何想法吗?感谢
class FollowButton extends React.Component {
constructor() {
super();
this.state = {};
this.state.following_state = true;
}
handleClick(event) {
event.preventDefault();
this.setState({following_state: !this.state.following_state});
let follow_state = following_state;
ProfilesDispatcher.dispatch({
action: FOLLOW,
follow_status: {
following: follow_state
}
});
}
render() {
let buttonText = this.state.following_state? "following" : "follow";
let activeState = this.state.following_state? 'active': '';
return (
<button className={classnames(this.props.styles, this.props.activeState)}
onClick={this.handleClick.bind(this)}>{buttonText}</button>
);
}
}
答案 0 :(得分:0)
正如@Felix King指出你正在使用和未定义的变量 following_state 。您应该定义此变量
const following_state = !this.state.following_state
并使用它来设置动作中的状态和follow_status。不要设置状态然后立即呼叫它,因为它不是同步呼叫,可能会或可能不会及时完成。
handleClick(event) {
event.preventDefault();
const following_state = !this.state.following_state
this.setState({following_state}); // You can do this in ES6, as shorthand for {following_state: following_state}
ProfilesDispatcher.dispatch({
action: FOLLOW,
follow_status: {
following: following_state
}
});
}