2017-02-22 75 views
0

我想在按鈕單擊時打開/渲染/顯示組件。我試圖通過改變狀態來做到這一點,但無法做到這一點。在按鈕單擊時渲染組件React ES6

我想渲染按鈕單擊組件。狀態發生變化,但組件不呈現。

export default class NewNav extends React.Component { 
    constructor(props) { 
    super(props); 
    this.state = { 
     date: new Date(), 
     login: false 
    }; 
    this.handleClick = this.handleClick.bind(this); 

    } 

    handleClick(e) { 
    this.state.login = true; 
    } 

    render() { 

    const style = { 
     margin: 12 
    }; 

    return (
     <MuiThemeProvider> 

     <div className="top-bar"> 
      <div className="top-bar-left"> 
      <ul className="menu"> 
       <li> 
       <RaisedButton 
        label="Sign Up" 
        style={style} 
        primary={false} 
        onClick={this.handleClick} 
        labelColor="#FFF" 
        backgroundColor="#00E676"/> 
       </li> 

      </ul> 
      </div> 
      <div className="top-bar-right"> 

      <ul className="menu"> 

       <li> 
       <RaisedButton 
        label="Log In" 
        primary={true} 
        className="btnLogin" 
        backgroundColor="#3AAA35"></RaisedButton> 

       </li> 

       <li> 
       <RaisedButton 
        label="Sign Up" 
        primary={false} 
        labelColor="#FFF" 
        backgroundColor="#00E676"/> 

       </li> 

      </ul> 
      {this.state.login 
       ? <FirstPage/> 
       : null 
} 

      </div> 

     </div> 
     </MuiThemeProvider> 

    ); 
    } 
} 

回答

0

不要設置state直接使用setState方法。否則,反應不知道狀態改變,不會重新渲染組件。

所以不是這樣的:

handleClick(e) { 
    this.state.login = true; 
    } 

使用本:

handleClick(e) { 
    this.setState({login: true}); 
    } 
+0

非常感謝! –

+0

不客氣。我很高興我可以幫助:) –

0

你實現改變狀態,而不讓陣營自知:根據documentation 你一個看到

setState()

執行nextState 到當前狀態的淺層合併。這是您用來從事件處理程序和服務器請求回調觸發UI 更新的主要方法。

第一個參數可以是一個對象(包含零個或多個要更新的鍵)或一個返回包含要更新的鍵的對象的狀態和道具的函數。

這裏是簡單對象用法:

this.setState({mykey: 'my new value'}); 

所以你的情況,你都應該使用這樣的事情來更新您的狀態:

handleClick(e) { 
    this.setState({login: true}); 
} 
+0

謝謝。是的,我意識到了錯誤。我錯誤地更新了狀態 –