ReactJs controlled component simple form
Hello React - controlled components - read and write. author(s): Ryan Vice
by karlovac
HTML
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src="https://fb.me/react-with-addons-0.14.0.js"></script>
<script src="https://fb.me/react-dom-0.14.0.js"></script>
<div id="view" />
CSS
div {
padding-right: 5px;
}
input {
margin: 5px;
}
Babel + JSX
// The state.externalVal is slow to update, which causes the IME composition to
// be interrupted. To compensate, when composing, we use a local
// state.localValue to update the controlled value quickly. This doesn't
// interrupt the IME composition.
// However, we still rely on the externalVal, so we switch back to it when the
// composition has ended.
var ExampleForm = React.createClass({
getInitialState: function() {
return {
// externalVal is the "source of truth," but it's slow to update (which
// will interrupt the IME composition). It may also change via an
// external event.
externalVal: '',
// Therefore we store a copy, localVal, that is quicker to update.
// We'll use this copy while we're composing, and using the externalVal
// otherwise.
localVal: ''}
},
onCompositionStart: function(e) {
this.setState({
// Make sure that localVal matches externalVal, in case externalVal
// has changed since the last onChange event.
localVal: this.state.externalVal,
isComposing: true
});
},
onCompositionEnd: function(e) {
this.setState({ isComposing: false });
},
onChange: function(e) {
const val = e.target.value;
this.setState({localVal: val});
// The requestAnimationFrame here simulates a slow async update.
window.requestAnimationFrame(() => {
const re = /^[\u4E00-\u9FA5]+$/;
let filteredVal = val;
if (!re.test(filteredVal)) {
filteredVal = '';
}
this.setState({externalVal: filteredVal});
});
},
render: function() {
const { isComposing, externalVal, localVal } = this.state;
return (
<div>
<input id='readAndWrite' className="form-control" type='text'
value={isComposing ? localVal : externalVal}
onCompositionStart={this.onCompositionStart}
onCompositionEnd={this.onCompositionEnd}
...