React 中是否仍然需要具有自动绑定和属性初始值设定项的构造函数

IT技术 reactjs ecmascript-6 es6-class ecmascript-next
2021-05-11 04:53:37

我正在重构一个基于 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),但我的代码似乎正在工作,我很困惑。

谢谢

3个回答

根据我的理解,在使用类属性时,您根本不需要键入构造函数(如在您的第二个代码示例中)。接受的答案指出,如果您“需要在初始状态对象中引用props”,则确实需要一个,但是如果您使用所述类属性,那么您可能正在使用 Babel 对其进行转译,在这种情况下是一个构造函数使用,它只是在幕后完成。因此,即使您在 state 中使用 props,也不需要自己添加构造函数。

有关更好的示例和更好的解释,请参阅这篇文章

您不需要显式定义的构造函数,除非您需要props在初始状态对象中引用

您不需要显式定义构造函数,然后执行 super(props)。您可以像下面的示例一样访问 props。即'prop1'

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


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


  render(){
  console.log(this.state.prop1);
   return(
       <div>Hi</div>
   );

   }
 }


 ReactDOM.render(<MySpecialComponent prop1={1}/> , mountNode);