以前我用它在 React JSX 组件中调用我的方法,这个方法给了我正确的输出
this.updateState.bind(this)
但是当我将上述语句替换为
() => this.updateState(...this)
这没有给我输出它返回未定义
以前我用它在 React JSX 组件中调用我的方法,这个方法给了我正确的输出
this.updateState.bind(this)
但是当我将上述语句替换为
() => this.updateState(...this)
这没有给我输出它返回未定义
你应该更换
() => this.updateState(...this)
和
(...args) => this.updateState(...args)
箭头函数从其父词法范围继承其上下文。
从箭头函数调用函数时,它继承自调用者的“this”引用。
在 React 中,您可以将函数绑定到this构造函数中。this在您的情况下未定义,因为函数未绑定到它。
constructor(props) {
super(props)
this.updateState = this.updateState.bind(this)
}
然后您可以正常使用该功能。无论如何,您不希望this每次使用该函数时都绑定该函数。
And if you have the transform class properties plugin for Babel, you can automatically bind a class function by defining it like
updateState = () => {
...
}
Transform class properties
updateState = () => {
...
}
Have a look on this: https://babeljs.io/docs/en/babel-plugin-transform-class-properties