注:代码都是经过转化后可以执行的
ES6 DEMO
class App extends React.Component{
constructor(props) {
super(props);
this.state = {
userInput: ''
}
}
handleChange(e) {
this.setState({userInput: e.target.value});
}
clearAndFocusInput() {
this.setState({userInput: ''}, function() {
this.refs.theInput.getDOMNode().focus(); // Boom! Focused!
});
}
render() {
return (
<div>
<div onClick={this.clearAndFocusInput}>
Click to Focus and Reset
</div>
<input
ref="theInput"
value={this.state.userInput}
onChange={this.handleChange}
/>
</div>
);
}
}
ES5 DEMO
var App = React.createClass({
getInitialState: function() {
return {userInput: ''};
},
handleChange: function(e) {
this.setState({userInput: e.target.value});
},
clearAndFocusInput: function() {
// Clear the input
this.setState({userInput: ''}, function() {
// This code executes after the component is re-rendered
this.refs.theInput.getDOMNode().focus(); // Boom! Focused!
});
},
render: function() {
return (
<div>
<div onClick={this.clearAndFocusInput}>
Click to Focus and Reset
</div>
<input
ref="theInput"
value={this.state.userInput}
onChange={this.handleChange}
/>
</div>
);
}
});
ES6的代码是需要预处理一下的,可以用babel