我正在构建一种带有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;
对于亲子沟通,只需传递道具。 https://facebook.github.io/react/tips/communicate-between-components.html – JordanHendrix