Communication between various components that do not have a parent-child relationship in the reaction

Suppose I have two different DOM elements

<div id="firstDiv">
</div>
<div id="secondDiv">
</div>

Now let's say that I render some html inside firstDiv using

React.render(firstComponent(null),document.getElementById('firstDiv');

Now let's say that I get some data from the server inside the firstComponent, and then I have to display some of the data inside the secondDiv , what is the best way to do this? Can I call React.renderComponent (, document.getElementById ("secondDiv")) from within firstComponent ?? And how to achieve two-way communication between them ??? Say now I click the link in the html displayed in the second Div, then how to change the text inside the firstDiv ??

If I summarize this question, it will be "How to visualize html inside several DOM elements from one component, and then exchange data with these components that appear in different DOM elements?"

+4
source share
2 answers

This can be achieved using regular parent-child relationships , unless you have no parent.

But you can still pass some functions to the root component that will be called inside the two components and start rendering

The following is a working demo of the example you set:

var First = React.createClass({
    render: function() {
        return <div>Hello1 {this.props.name}</div>;
    }
});


var Second = React.createClass({
    render: function() {
        return <div onClick={this.props.onSecondClicked}>Hello2 {this.props.name}</div>;
    }
});

function onSecondClicked() {
    React.render(<First name="World updated!" />, document.getElementById("first"));
}

React.render(<First name="World" />, document.getElementById("first"));

React.render(<Second name="World" onSecondClicked={onSecondClicked}/>, document.getElementById("second"));

JsFiddle link


React.render ( , , ). .

" ", .

, .

+1

, , .

, Flux, Facebook React, . Inside Flux, :

  • firstComponent (), ( / ), , . , Store (change), ", , "
  • , , , , (, getState()). , .
  • secondComponent (, onClick), , ( -API) Flux Action ( JS-), Store . ( , )
    • , Hello World Hello, World! I'm updated.
    • , .
+1

All Articles