注:代码都是经过转化后可以执行的
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 (
<p>
<p onClick={this.clearAndFocusInput}>
Click to Focus and Reset
</p>
<input
ref="theInput"
value={this.state.userInput}
onChange={this.handleChange}
/>
</p>
);
}
}
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 (
<p>
<p onClick={this.clearAndFocusInput}>
Click to Focus and Reset
</p>
<input
ref="theInput"
value={this.state.userInput}
onChange={this.handleChange}
/>
</p>
);
}
});
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
ES6的代码是需要预处理一下的,可以用babel
浏览器不一定支持 ES6 ,所以下载个 babel 把 ES6 「翻译」成 ES5 就好了
这是在 ES6 中作用域的问题, 你可以将操作函数在 constructor 中绑定 this
在 stage-0 也可以通过箭头函数定义 handleChange:
另外在传递属性的时候也可以: