javascript - How to communicate between independent components in React.JS? - Stack Overflow

I'm newbie in React.JS and trying to understand the following thing. Imagine that I have two ponen

I'm newbie in React.JS and trying to understand the following thing. Imagine that I have two ponents: two HTML text inputs; what I want to achieve is the following: when a user changes the text in first text field - changes appears at the same time in a second text field; and vice versa - when a user changes the text in second text filed - the change also appears in the first one. What is the right way to do it in a react way? What should be written in the onChange handlers?

I'm newbie in React.JS and trying to understand the following thing. Imagine that I have two ponents: two HTML text inputs; what I want to achieve is the following: when a user changes the text in first text field - changes appears at the same time in a second text field; and vice versa - when a user changes the text in second text filed - the change also appears in the first one. What is the right way to do it in a react way? What should be written in the onChange handlers?

Share Improve this question edited May 24, 2014 at 23:02 secretformula 6,4324 gold badges34 silver badges56 bronze badges asked May 24, 2014 at 21:34 Artem VorobyevArtem Vorobyev 1851 silver badge9 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 4

Personally I like an event-driven approach. It's easy to implement a Pub/Sub pattern either using a little library (such as PubSubJS) or rolling your own with native events.

I wrote a little more about the latter here: http://maketea.co.uk/2014/03/05/building-robust-web-apps-with-react-part-1.html#ponent-munication

As long as both your form inputs are (1) controlled inputs and (2) have a value property pointing to the same data, any change to that data will update both inputs.

/** @jsx React.DOM */

var SyncEdit = React.createClass({
  getInitialState: function() {
    return { text: "" };
  },

  render: function() {
    return (
      <div>
        <input type="text" value={this.state.text} onChange={this.handleChange} />
        <input type="text" value={this.state.text} onChange={this.handleChange} />
      </div>
    );
  },

  handleChange: function(evt) {
    this.setState({text: evt.target.value});
  }
});

React.renderComponent(<SyncEdit />, document.body);

Here's a JSFiddle to demonstrate: http://jsfiddle/BinaryMuse/2K5qX/

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744376281a4571201.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信