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?
2 Answers
Reset to default 4Personally 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条)