this.props 在 React 组件中的箭头函数中显示为未定义

this.props shows as undefined in an arrow function within React Component

我正在使用箭头函数在 React 组件内绑定 this。请参阅下面的 handleChange() 函数。当我在箭头函数中放置一个断点时,我发现了一些很奇怪的事情:定义了 this,但是 this.propsundefined。尽管如此,this.props.onChange() 还是被正确调用了!!!对这种奇怪的行为有解释吗?

class MyComponent extends React.Component {
    render() {
        const { someProp } = this.props;

        // <TextField> is an input component from Material UI library
        return (
            <TextField
                onChange={this.handleChange}
            />
        );
    }

    handleChange = event => {
        const value = event.target.value;
        this.props.onChange(value);
    };
}

P.S。另一方面,render() 方法正常运行 - this.props 已定义。

更新

这是 Babel 生成的转译代码:

_this.handleChange = function(event) {
    var value = event.target.value;
    _this.props.onChange(value);
}

更有可能的是,您被 babel 欺骗了。

由于您使用的是 babel-preset < 2017,因此转译代码:

class A {
  method = () => {
    this.prop.a();
  };
}

look something like:

var A = function A() {
  var _this = this;

  this.method = function () {
    _this.prop.a();
  };
};

查看上面的代码,method 中的 _thisthis 似乎都指向 class 实例(因为 this in a function called as a method of an object binds to that object)。

然而,在 JS this is a dynamic property 中,我们无法仅通过阅读代码以可预测的方式静态地确定其值;我们必须运行它。

这意味着 handleChange 中的 this 不一定与您期望的 this 相同。这取决于 handleChange 的调用方式。但是,无论我们如何调用 handleChange_this 都不会受到影响(这也是 Babel 这样做的原因之一)

在您的特定代码中,您将 handleChange 传递给 TextFieldonChange 事件处理程序,它将覆盖 thisundefined默认。

React 事件处理程序将上下文覆盖为 undefined(按 calling the handler as a plain function):

ReactDOM.render(
  <input onChange={logThis} placeholder="Start typing" />,
  document.querySelector('#example')
)

function logThis() {
  console.log(this);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="example"></div>

这意味着在 handleChange 中,thisTextField 设置的约束,而 _this 仍然指向 MyComponent 的实例。

因此一切仍然有效(因为 _this 是正确的),但 this 很可能是 undefined.