2015-09-25 100 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

相關問題