[英]Sharing Properties between React Components
我正在用 React 構建一種時鍾,它可以選擇在一個組件中遞增或遞減一個數字(默認為 25),而在另一個組件中,它將計時器(從 25 點開始的 25:00)更新為任何number 增加或減少到。
我有兩個組件(會話和時鍾)成功地執行了它們自己的操作,但是我對如何讓計數器(會話組件)更新時鍾組件中的計時器狀態感到困惑。 更具體地說,我一直在this.props.minutes
無濟於事。
問題:如何在組件之間共享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;
您需要像這樣將狀態從 Session 傳遞到 Clock:
<Clock time={this.state.minutes} />
在你的 Session 組件中
然后“狀態”現在可用於您的時鍾組件作為this.props.time
或者你在上面的代碼中叫它什么。
這個故事的寓意是從父組件傳遞到子組件的狀態是使用道具完成的
相關文檔:
https://facebook.github.io/react/docs/multiple-components.html
編輯:文檔中的另一個關鍵鏈接:
https://facebook.github.io/react/tips/communicate-between-components.html
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.