[英]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.