我目前正在开发一个React应用,当组件类具有许多功能时,我发现必须绑定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插件来绑定方法,这是ES7的一项实验功能。确保启用stage-0才能使用它。
[这允许在定义类方法时利用箭头函数,利用箭头函数的词法绑定,因此this
引用函数的上下文(在本例中为类),如下所示:
class Foo extends Component {
boundFunction = () => { /* 'this' points to Foo */ }
}
您可以使用以下方法将其缩短一点:
this.function1 = :: this.function1