【问题标题】:Refactoring react this binding重构对此绑定作出反应
【发布时间】:2019-09-09 11:00:16
【问题描述】:

我有这个代码

class BottomPanel extends React.Component<Props, {}> {
  constructor(props) {
    super(props);
    this.dropDownUpdate = this.dropDownUpdate.bind(this);
  }

  dropDownUpdate = e => this.setState({ dropDownValue: e.currentTarget.textContent });

我想知道我是否可以重构

this.dropDownUpdate = this.dropDownUpdate.bind(this);

this.dropDownUpdate = this.dropDownUpdate;

如果是这样,为什么或为什么不呢?我只是在某处看到它正在这样做

this.dropDownUpdate = this.dropDownUpdate;

我不确定是否可以将其应用到我的代码中。

【问题讨论】:

  • 你试过了吗?
  • 是的,我认为到目前为止它正在工作。但是,除非我明白为什么,否则我真的不想使用它。
  • 如果没有this.dropDownUpdate = this.dropDownUpdate.bind(this); 行,它的工作方式是否相同?

标签: reactjs


【解决方案1】:

有一点需要注意,当你写的时候:

class BottomPanel extends React.Component<Props, {}> {
  dropDownUpdate = e => this.setState({ dropDownValue: e.currentTarget.textContent });
}

这(当前)不是有效的 ES6 语法。您不能以这种方式分配带有等号的类变量。它起作用的原因是transform-class-properties babel 插件,更多内容见下文。

查看这个问题和答案了解更多详情:

ES6 class variable alternatives

从技术上讲,声明类变量的正确方法是使用 this 关键字,例如:

class BottomPanel extends React.Component<Props, {}> {
  constructor(props) {
      this.dropDownUpdate = this.dropDownUpdate.bind(this)
  }

   dropDownUpdate(e) {
       this.setState({ dropDownValue: e.currentTarget.textContent });
   }
}

为什么你不能这样做:

class BottomPanel extends React.Component<Props, {}> {
  constructor(props) {
      this.dropDownUpdate =e => this.setState({ dropDownValue: e.currentTarget.textContent });
  }
}

看到这个帖子:Can I use arrow function in constructor of a react component?

现在问题是 - 我假设你正在使用 Create React App - transform-class-properties babel 插件附带 - 这就是第一个声明有效的原因。

看看这个问题,了解您为什么要使用this.dropDownUpdate = this.dropDownUpdate.bind(this); 技巧。这不是必需的 - 但您会遇到调试器问题(浏览器不知道 transform-class-properties babel 转换)。

Chrome, Firefox debuggers not displaying the correct value for 'this' in a react app

否则你可以清除你的类方法,比如:

class BottomPanel extends React.Component<Props, {}> {
  dropDownUpdate = e => this.setState({ dropDownValue: e.currentTarget.textContent });
}

【讨论】:

    【解决方案2】:

    由于 dropDownUpdate 是一个箭头函数,它应该可以在没有

    的情况下正常工作

    this.dropDownUpdate = this.dropDownUpdate;

    this.dropDownUpdate = this.dropDownUpdate.bind(this);

    在箭头函数中,this 的值是词法绑定的,不像常规函数,this 的值会根据调用函数的上下文而变化。

    【讨论】:

    【解决方案3】:

    只需如下定义您的函数。

    dropDownUpdate = (事件) => { …… }

    它不需要在构造函数中绑定

    【讨论】:

    • 这仅适用于您使用transfrom-class-properties babel 插件(create-react-app 附带)
    猜你喜欢
    • 2017-11-08
    • 2019-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-18
    • 2012-08-05
    相关资源
    最近更新 更多