我正在重构一个使用常规构造函数的基于es6类的React组件,然后绑定方法,并在该构造函数内定义状态/属性。像这样:
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 }) } }
我想对此进行重构,以便自动绑定功能,并对状态和属性使用属性初始化器。现在我的代码看起来像这样:
class MySpecialComponent extends React.Component { state = { thing: true } myAttribute = { amazing: false } myMethod = (e) => { this.setState({ thing: e.target.value }) } }
我的问题是,我仍然需要构造函数吗?还是道具也自动绑定?我本来希望仍然需要构造函数和include super(props),但是我的代码似乎正在工作并且感到困惑。
super(props)
谢谢
根据我的理解,使用类属性时根本不需要键入构造函数(如第二个代码示例中所示)。公认的答案表明,如果“需要在初始状态对象中引用道具”确实需要一个,但是如果使用上述类属性,则可能是使用Babel进行转换,在这种情况下为构造函数 在 使用时,它只是被在幕后完成。因此,即使您在状态下使用道具,也无需自己添加构造函数。
有关更好的示例和更好的说明,请参见此文章。