2015-09-25 99 views
1

我想用handleClick()函数实现3件事情。将buttonText切换为跟随或跟随,切换'active'类并处理FOLLOW动作。我可能做得不对。出于某种原因,onClick事件对此没有任何影响。有任何想法吗?由于处理ReactJs中的状态变化

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

您是否在控制台中看到错误?我认为你需要 onClick = {this.handleClick} –

+0

你应该在控制台中看到refrences错误,因为'following_state'没有在任何地方声明。我假设你想'var follow_state = this.state.following_state;'。 –

+0

不,我没有在控制台中看到任何错误。那是奇怪的事情。 React 0.14需要点击事件才能使用bind() – hilarl

回答

0

由于@Felix王指出你正在使用和未定义的变量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 
     } 
     }); 
    } 
+0

点击处理程序似乎并没有被解雇。我只是用你的解决方案更新代码。我得到'错误:invariant.js:39未捕获的错误:不变的违规:预期onClick监听器是一个函数,而不是类型字符串'我不知道这是否相关。 – hilarl

+0

你可以检查你的类名(this.props.styles,this.props.activeState)是否正常工作?您似乎正确使用了onClick。 – ArneHugo

相关问题