在React中仍然需要带有自动绑定和属性初始化器的构造函数吗 [英] Is the constructor still needed in React with autobinding and property initializers

查看:132
本文介绍了在React中仍然需要带有自动绑定和属性初始化器的构造函数吗的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在重构一个使用常规构造函数的基于es6类的React组件,然后绑定方法,并在该构造函数内定义状态/属性.像这样:

I am refactoring an es6 class based React component that uses the normal constructor, and then binds methods, and defines state/attributes within that constructor. Something like this:

class MySpecialComponent extends React.Component {
  constructor(props) {
   super(props)
   this.state = { thing: true }
   this.myMethod = this.myMethod.bind(this)
   this.myAttribute = { amazing: false }
  }

  myMethod(e) {
   this.setState({ thing: e.target.value })
  }
}

我想重构它,以便我自动绑定函数,并使用属性初始化器来表示状态和属性.现在我的代码看起来像这样:

I want to refactor this so that I am autobinding the functions, and using property initializers for the state and attributes. Now my code looks something like this:

class MySpecialComponent extends React.Component {
  state = { thing: true }
  myAttribute = { amazing: false }


  myMethod = (e) => {
   this.setState({ thing: e.target.value })
  }
}

我的问题是,我仍然需要构造函数吗?还是道具也自动绑定?我本来希望仍然需要构造函数并包含super(props),但是我的代码似乎正在运行并且感到困惑.

My question is, do I still need the constructor? Or are the props also autobound? I would have expected to still need the constructor and included super(props), but my code seems to be working and I'm confused.

谢谢

推荐答案

据我了解,使用类属性(如您的第二个代码示例中所示).公认的答案指出,如果需要在初始状态对象中引用道具"确实需要一个,但是如果您使用上述的类属性,则可能是使用Babel进行转换,在这种情况下为构造函数,它只是在幕后完成.因此,即使您在状态下使用道具,也无需自己添加构造函数.

From my understanding, you don't need to type out a constructor at all when using class properties (as in your second code example). The accepted answer states that you do need one if you "need to reference the props in your initial state object," but if you're using said class properties, then you're probably using Babel to transpile it, in which case a constructor is used, it's just being done behind the scenes. Because of this, you don't need to add a constructor yourself, even if you are using props in state.

有关更好的示例,请参见此文章以及更好的解释.

See this aricle for better examples and a better explanation.

这篇关于在React中仍然需要带有自动绑定和属性初始化器的构造函数吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆