在 React Component 类 中绑定 'this' 有没有更好的方法?
Is there a better way to bind 'this' in React Component classes?
我目前正在开发一个 React 应用程序,我发现当一个组件 class 有很多功能时必须绑定 this
有点麻烦。
例子
class Foo extends Component {
constructor(props){
super(props);
this.function1 = this.function1.bind(this);
this.function2 = this.function2.bind(this);
this.function3 = this.function3.bind(this);
}
function1() {
...
}
function2() {
...
}
function3() {
...
}
}
有没有更有效的方法来做到这一点?
您可以通过使用 transform-class-properties Babel plugin, which is an experimental ES7 feature. Make sure you enable stage-0 来避免必须绑定方法才能使用它。
这允许在定义 class 方法时使用箭头函数,利用箭头函数的词法绑定,因此 this
指的是函数的上下文(在本例中为 class),像这样:
class Foo extends Component {
boundFunction = () => { /* 'this' points to Foo */ }
}
您可以通过以下方式缩短它:
this.function1 = ::this.function1
我目前正在开发一个 React 应用程序,我发现当一个组件 class 有很多功能时必须绑定 this
有点麻烦。
例子
class Foo extends Component {
constructor(props){
super(props);
this.function1 = this.function1.bind(this);
this.function2 = this.function2.bind(this);
this.function3 = this.function3.bind(this);
}
function1() {
...
}
function2() {
...
}
function3() {
...
}
}
有没有更有效的方法来做到这一点?
您可以通过使用 transform-class-properties Babel plugin, which is an experimental ES7 feature. Make sure you enable stage-0 来避免必须绑定方法才能使用它。
这允许在定义 class 方法时使用箭头函数,利用箭头函数的词法绑定,因此 this
指的是函数的上下文(在本例中为 class),像这样:
class Foo extends Component {
boundFunction = () => { /* 'this' points to Foo */ }
}
您可以通过以下方式缩短它:
this.function1 = ::this.function1