React: Avoid Managed Components

So, I'm just asking out of curiosity,

Has anyone found a smart way to handle the binding of two-way data in managed components (input, selection, ...) without having to write all of the following:

getInitialState: function() { return {value: 'Hello!'}; }, handleChange: function(event) { this.setState({value: event.target.value}); }, render: function() { var value = this.state.value; return <input type="text" value={value} onChange={this.handleChange} />; } 
+6
source share
2 answers

You might want to read the Bilateral Binding Assistants section of the documentation: http://facebook.imtqy.com/react/docs/two-way-binding-helpers.html

There is a LinkedStateMixin :

 var NoLink = React.createClass({ getInitialState: function() { return {message: 'Hello!'}; }, handleChange: function(event) { this.setState({message: event.target.value}); }, render: function() { var message = this.state.message; return <input type="text" value={message} onChange={this.handleChange} />; } }); var WithLink = React.createClass({ mixins: [React.addons.LinkedStateMixin], getInitialState: function() { return {message: 'Hello!'}; }, render: function() { return <input type="text" valueLink={this.linkState('message')} />; } }); 
+5
source

A trick worth knowing - since the onChange event onChange bubbling up, you can insert form inserts into the container and register onChange , instead - <form> perfect for this.

Then you can write a general onChange handler that extracts data from the target event - you will need to add some identifying information to the field, which is the name attribute.

Here is a Gist with an approximate implementation and a live demonstration of this in action - the form input state is displayed under the form.

+4
source

Source: https://habr.com/ru/post/978093/


All Articles