Max*_*ton 10 ecmascript-6 reactjs ecmascript-next es6-class
我正在重构一个基于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 })
}
}
Run Code Online (Sandbox Code Playgroud)
我想重构这个,以便我自动绑定函数,并使用属性初始化器的状态和属性.现在我的代码看起来像这样:
class MySpecialComponent extends React.Component {
state = { thing: true }
myAttribute = { amazing: false }
myMethod = (e) => {
this.setState({ thing: e.target.value })
}
}
Run Code Online (Sandbox Code Playgroud)
我的问题是,我还需要构造函数吗?或道具也是autobound?我本来希望仍然需要构造函数和包含super(props)
,但我的代码似乎工作,我很困惑.
谢谢
小智 7
除非需要props
在初始状态对象中引用,否则不需要显式定义的构造函数.
归档时间: |
|
查看次数: |
6193 次 |
最近记录: |