2016-03-31 145 views
1

我正在構建一種帶有React的時鐘,它具有在一個組件中增加或減少數字(默認爲25)的選項,而在另一個組件中它更新定時器(自我們從25開始)增加或減少數字。我有兩個組件(會話和時鐘)成功地執行自己的操作,但是我很難理解如何讓計數器(會話組件)更新時鐘組件中的計時器狀態。更具體地說,我一直玩弄this.props.minutes無濟於事。在React組件之間共享屬性

問題:我怎樣才能在組件之間共享this.state.minutes屬性?先謝謝你。我仍然是React的初學者。

會議:

const Session = React.createClass({ 

    getInitialState: function() { 
    return { 
     minutes: 25, 
     seconds: 0 
    }; 
    }, 

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

    decrement: function() { 
    this.setState({ minutes: this.state.minutes - 1 }); 
    }, 

    timeToString: function(time) { 
    return time + ':00'; 
    }, 

    render: function() { 
    return (
     <section> 
     <button onClick={this.increment}>+</button> 
     <button onClick={this.decrement}>-</button> 
     {this.state.minutes} 
     <Clock/> 
     </section> 
    ); 
    } 

}); 

module.exports = Session; 

時鐘:

const Clock = React.createClass({ 

    getInitialState: function() { 
    return { currentCount: 10 }; 
    }, 

    startTimer: function() { 
    var intervalId = setInterval(this.timer, 1000); 
    this.setState({ intervalId: intervalId }); 
    }, 

    pauseTimer: function() { 
    clearInterval(this.state.intervalId); 
    this.setState({ intervalId: this.state.currentCount }); 
    }, 

    timer: function() { 
    var newCount = this.state.currentCount - 1; 
    if (newCount >= 0) { 
     this.setState({ currentCount: newCount }); 
    } else { 
     clearInterval(this.state.intervalId); 
    } 
    }, 

    render: function() { 
    return (
     <section> 
     <button onClick={this.startTimer}>Start</button> 
     <button onClick={this.pauseTimer}>Pause</button> 
     {this.state.currentCount} 
     </section> 
    ); 
    } 

}); 

module.exports = Clock; 
+0

對於親子溝通,只需傳遞道具。 https://facebook.github.io/react/tips/communicate-between-components.html – JordanHendrix

回答

1

你需要從會話的狀態傳遞給時鐘像這樣:

<Clock time={this.state.minutes} />在你的會話組件

然後「狀態」現在可用於您的時鐘組件,如this.props.time

或任何你在上面的代碼中調用它。

道德的故事是國家從父組件傳下來的一個子組件使用道具

相關的文檔是這樣做的:

https://facebook.github.io/react/docs/multiple-components.html

編輯:在另一個關鍵環節文檔:

https://facebook.github.io/react/tips/communicate-between-components.html

+0

謝謝!我不相信我沒有意識到這一點。 – Jose

+0

同樣的事情發生在我身上!,我確信它是一個常見的錯誤 – JordanHendrix