2016-03-31 148 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