2017-02-13 121 views
2

我開始使用React玩遊戲,我被這個示例卡住了。反應改變狀態鍵?

計數器的工作原理,但爲什麼onClick按鈕不改變鍵狀態激活並呈現正確的按鈕?

鏈接CodePen

const Button = ({label}) => (
    <button className="btn btn-primary">{label}</button> 
); 

const Counter = React.createClass({ 

    getInitialState: function() { 
     return { 
      counter: 0, 
      active: false 
     } 
    }, 

    increment: function() { 
     this.setState({ 
      counter: this.state.counter + 1 
     }) 
    }, 

    change: function() { 
     this.setState({ 
      active: true 
     }) 
    }, 

    render: function() { 
     return (
       <div> 
        <h1>Counter: {this.state.counter}</h1> 
        <button onClick={this.increment}>1+</button>} 
        {this.state.active ? 
        <Button label="Sign OUT"/> : 
        <Button label="Sign in" onClick={this.change}/>} 
       </div> 
     ) 
    } 
}); 

ReactDOM.render(<Counter/>, document.getElementById("root")) 

回答

0

因爲您忘記在Button中定義click事件組件使用:

const Button = (props) => (
    <button className="btn btn-primary" onClick={props.onClick}>{props.label}</button> 
); 

一件事,你需要signout按鈕也定義click事件,像這樣:

{this.state.active ? 
    <Button label="Sign OUT" onClick={this.change}/> : 
    <Button label="Sign in" onClick={this.change}/> 
} 

change: function() { 
    this.setState({ 
     active: !this.state.active 
    }) 
} 

檢查工作示例:

jsfiddlehttps://jsfiddle.net/mtbg3g59/

Codepenhttp://codepen.io/anon/pen/WRLgpp

+0

感謝那些幫助了很多 – Darius

+0

高興,幫你:) –

1

您的按鈕不採取命名的onClick道具所以這是正常的T帽子就什麼也不做,嘗試它的定義改變這一點,它應該工作

const Button = ({label}, {onClick}) => (
    <button className="btn btn-primary" onClick={onClick}>{label}</button> 
); 
0

在頁面加載this.state.active被設置爲false,因此呈現「Sign OUT」按鈕,其沒有onCl ick屬性。我想你想你的代碼看起來是這樣的:

{this.state.active ? 
       <Button label="Sign OUT" onClick={this.change}/> : 
       <Button label="Sign in"/>}