I've made a small fiddle to show the problem: http://jsfiddle.net/4TpnG/582/ When you have an input box with onBlur attached to it, and an initial value from state, input from the keyboard is blocked. When onChange is attached, it's working correctly. Why is this happening and how can this be solved? I would have expected it to accept the characters you type and update the state onBlur.
var Test = React.createClass({
getInitialState: function() {
return {
value: "hallo"
};
},
render: function() {
return ( < form >
< div >
Onchange: < input type = "text"
value = {
this.state.value
}
onChange = {
this.handleChange
}
/><br/ >
Onblur: < input type = "text"
value = {
this.state.value
}
onBlur = {
this.handleChange
}
/>
</div >
< /form>
);
},
handleChange: function(e){
this.setState({value: e.target.value});
}
});
React.renderComponent(<Test/ > , document.body);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.12.2/react-with-addons.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.12.2/JSXTransformer.js"></script>
The value
attribute ties the value of the input to that state, and if the user changes the value then the state and the input value is no longer tied to each other. So React stops that from happening.
You probably want to use the defaultValue
attribute instead.
If you want to use the value
attribute you need the onChange
to sync it with the component state. This because the component can re-render at any time, and if the value is out of sync with the state that would render an old value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With