我正在重构一个基于 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 })
}
}
我的问题是,我还需要构造函数吗?或者props也是自动绑定的?我原以为仍然需要构造函数和包含super(props)
,但我的代码似乎正在工作,我很困惑。
谢谢