我刚接触使用带有React的ES6类,之前我已经将我的方法绑定到当前对象(在第一个示例中显示),但ES6是否允许我使用箭头将类函数永久绑定到类实例?(当作为回调函数传递时很有用.)当我尝试使用它时,我遇到错误,就像使用CoffeeScript一样:
class SomeClass extends React.Component {
// Instead of this
constructor(){
this.handleInputChange = this.handleInputChange.bind(this)
}
// Can I somehow do this? Am i just getting the syntax wrong?
handleInputChange (val) => {
console.log('selectionMade: ', val);
}
Run Code Online (Sandbox Code Playgroud)
因此,如果我要传递SomeClass.handleInputChange
给setTimeout
它,那么它将被限定为类实例,而不是window
对象.
class SomeClass extends Component{
someEventHandler(event){
}
render(){
return <input onChange={------here------}>
}
}
Run Code Online (Sandbox Code Playgroud)
我看到不同版本的------here------
部分.
// 1
return <input onChange={this.someEventHandler.bind(this)}>
// 2
return <input onChange={(event) => { this.someEventHandler(event) }>
// 3
return <input onChange={this.someEventHandler}>
Run Code Online (Sandbox Code Playgroud)
版本有何不同?或者只是一个偏好问题?
谢谢大家的回答和评论.都是有帮助的,我强烈建议阅读此链接FIRST如果你是这个困惑了我.
http://blog.andrewray.me/react-es6-autobinding-and-createclass/
巴贝尔正在发挥其魔力,这使我对正在发生的事情感到非常困惑.
这个反应组件中foo和bar之间有什么区别?什么时候应该使用哪个?
class MyComponent extends Component {
foo() {
//...
}
bar = () => {
//...
}
}
Run Code Online (Sandbox Code Playgroud)
(我自己的猜测是foo在原型中,bar在构造函数中?反正我不知道我在说什么)