1

以前我用它在 React JSX 组件中调用我的方法,这个方法给了我正确的输出

this.updateState.bind(this)

但是当我将上述语句替换为

() => this.updateState(...this)

这没有给我输出它返回未定义

4

3 回答 3

5

你应该更换

 () => this.updateState(...this)

 (...args) => this.updateState(...args)

箭头函数从其父词法范围继承其上下文。
从箭头函数调用函数时,它继承自调用者的“this”引用。

于 2018-10-01T08:52:18.493 回答
1

在 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 = () => {
  ...
}
于 2018-10-01T08:57:16.167 回答
1

Transform class properties

updateState = () => {
  ...
}

Have a look on this: https://babeljs.io/docs/en/babel-plugin-transform-class-properties

于 2018-10-01T09:11:02.683 回答