yakczh
V2EX  ›  问与答

reactjs 里面,组件相互之间怎么通信呢?

  •  
  •   yakczh · Jan 17, 2015 · 5823 views
    This topic created in 4162 days ago, the information mentioned may be changed or developed.
    <!DOCTYPE html>
    <html>
    <head>
    <title>Timer</title>

    <style type="text/css">

    #timer{
    float:right;width:500px;
    background:gold;
    }
    #message{
    background:yellowgreen;
    margin-right:500px;
    }

    </style>


    <script src="/js/reactjs/build/react.js"></script>
    <script src="/js/reactjs/build/JSXTransformer.js"></script>



    </head>
    <body>

    <blockquote>
    <div id="timer" ></div>

    <div id="message"></div>

    </blockquote>

    <script type="text/jsx">
    /** @jsx React.DOM */
    var Timer = React.createClass({
    getInitialState: function() {
    return {secondsElapsed: 0};
    },
    tick: function() {
    this.setState({secondsElapsed: this.state.secondsElapsed + 1});
    },
    componentDidMount: function() {
    console.log("started");
    this.interval = setInterval(this.tick, 1000);
    },
    render: function() {
    return (
    <h1>Seconds Elapsed: {this.state.secondsElapsed}</h1>
    );
    }
    });

    React.renderComponent(
    <Timer />,
    document.getElementById('timer')
    );

    var Message = React.createClass({
    render: function() {
    return <h1>Hello, <br/> {this.props.name}!</h1>;
    }
    });

    React.renderComponent(
    <Message name="xxxWorld" />,
    document.getElementById('message')
    );

    </script>
    </body>
    </html>

    比如两个组件,左面是信息 右面是定时器,如果要实现定时器超过100以后,改变左面的信息,怎么样实现通知呢?
    3 replies    2015-01-17 19:57:07 +08:00
    bcxx
        1
    bcxx  
       Jan 17, 2015
    加一个 model,让两个 view 都和这个 model 的值(即计时器的时间)进行绑定。
    yakczh
        2
    yakczh  
    OP
       Jan 17, 2015
    @bcxx 绑定是用 this.refs 吗?
    damngood
        3
    damngood  
       Jan 17, 2015
    记得 React 官网有建议. 甚至官方给出了个 Dispacher 组件实现的.
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   3108 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 32ms · UTC 14:40 · PVG 22:40 · LAX 07:40 · JFK 10:40
    ♥ Do have faith in what you're doing.