Just learning React and I have seen various different ways to get a value from a text input. I wanted ask whether all of them are correct or if there are any advantages to using one over another.
Method 1):
MyForm = React.createClass({
getInitialState: function() {
return {
username: ""
};
},
onSubmit: function(e) {
e.preventDefault();
this.setState({
username: this.refs.username.getDOMNode().value
});
/* Do something... */
},
render: function(){
return (
<div>
<form onSubmit={this.onSubmit} id="login-form">
<input type="text" ref="username"></input>
</form>
</div>
)
}
});
Method 2):
MyForm = React.createClass({
getInitialState: function() {
return {
username: ""
};
},
handleUsernameChange: function(evt) {
this.setState({
username: evt.target.value
});
},
onSubmit: function(e) {
e.preventDefault();
/* Do something... */
},
render: function(){
return (
<div>
<form onSubmit={this.onSubmit} id="login-form">
<input type="text" onChange={this.handleUsernameChange}></input>
</form>
</div>
)
}
});