JSFiddle - React, Tailwind, and code Playground
HTML
<script src="http://fb.me/react-with-addons-0.12.0.js"></script>
<script src="http://fb.me/JSXTransformer-0.12.0.js"></script>
<script src="http://fb.me/react-js-fiddle-integration.js"></script>
JavaScript 1.7
function asyncInput (ctor) {
// close over an event counter
var i = 0;
return React.createClass({
getInitialState: function () {
return {value: this.props.value}
},
onChange: function (e) {
var handler = this.props.onChange
if (handler) {
// handlers must adapt to a new protocol, identifying
// each state change with a version
handler(e, ++i)
this.setState({value: e.target.value, i: i})
}
},
componentWillReceiveProps: function (newProps) {
// only accept the latest value from props
if (newProps.i == this.state.i) {
this.setState({value: newProps.value})
}
},
render: function () {
return React.createElement(
ctor,
React.__spread({}, this.props, {
value: this.state.value,
onChange: this.onChange
}),
this.props.children
)
}
})
}
var AI= asyncInput('input');
var Test = React.createClass({
// the controlling component must track
// the version
change: function(e, i) {
var v = e.target.value;
setTimeout(function() {
this.setState({v: v, i: i});
}.bind(this), Math.floor(Math.random() * 100 + 50));
},
getInitialState: function() { return {v: ''}; },
render: function() {
{/* and pass it down to the controlled input, yuck */}
return <AI value={this.state.v} i={this.state.i} onChange={this.change} />
}
});
React.render(<Test />, document.body);