渲染重构会导致未定义的函数

Render refactoring leads to undefined function

本文关键字:未定义 函数 重构      更新时间:2024-01-05

我有一个React类,当这样写时,它可以正常工作:

const LoginContainer = React.createClass({
  authenticate: () => {
      console.log('TODO: Finish authenticating');
  },
  render: function() {
      return (
        <Login authenticate={this.authenticate} />
      );
    }
});

为了符合我们正在使用的样式指南,我应该使用箭头缩写render:

render: () =>
  (
    <Login authenticate={ this.authenticate } />
  ),

然而,一旦我重写了这个,我就会得到

未捕获的类型错误:无法读取未定义的属性"authenticate"

如何在箭头函数中获得对authenticate的引用?

请注意,我知道this的值在箭头函数中的作用域不同,但我试图弄清楚的是如何在React类中获得正确的绑定。这可能比普通JS更像是一个React问题。

Arrow函数在词汇上绑定上下文,以便this引用外部作用域的上下文。