【问题标题】:Is there anyway to get rid of binding `this` to `Component` functions in react?有没有办法摆脱将`this`绑定到`Component`函数的反应?
【发布时间】:2021-11-07 01:08:43
【问题描述】:

当我想让我的类函数的this 绑定到类(组件)实例时,我会这样做。在 React 中有没有更简单/更合适的方法来做到这一点?

class App extends Component {

  state = {
    currentSection: 1,
    message :{text:''}
  };

 
  constructor(props) {
    super(props);
    this.prevSection = this.prevSection.bind(this);
    this.nextSection = this.nextSection.bind(this);
    this.mobileChanged = this.mobileChanged.bind(this);
  }
}

【问题讨论】:

  • 另一种选择是不使用类。然后你可以避免使用this。像您所做的那样使用绑定将使原型上的方法可用。如果在调用构造函数之前不关心方法是否可以访问,请使用箭头函数。 stackoverflow.com/questions/31362292/…

标签: javascript reactjs ecmascript-6


【解决方案1】:

如果我没记错的话,如果你改变:

function nextSection() {...}

const nextSection = () => {...}

此更改后,您可以删除 thisbind

请让我知道您的组件是否会像以前一样保持功能。我不确定这是否会改变行为。

【讨论】:

  • 其实不能包含const,而只能包含nextSection = () => {...}。就像你一样,我已经放弃类组件太久了,以至于我几乎忘记了如何编写它。 ;)
【解决方案2】:

您可以使用arrow function 代替类方法

使用arrow function,将没有this context,因此您不必绑定它

class App extends Component {
  state = {
    currentSection: 1,
    message: { text: '' },
  };

  prevSection = () => {}

  nextSection = () => {}

  mobileChanged = () => {}
}

活生生的例子:

【讨论】:

  • 那么哪种做法更好呢?使用简单的类函数和绑定与箭头函数?
  • @Ehsan88 任何都可以。如果可能,您可以避免使用类组件。
  • @Ehsan88 关心并没有太大区别,您宁愿优先考虑human-readable 代码。
猜你喜欢
  • 1970-01-01
  • 2022-01-10
  • 1970-01-01
  • 1970-01-01
  • 2011-06-15
  • 2016-03-16
  • 1970-01-01
  • 2022-01-03
  • 2019-05-27
相关资源
最近更新 更多