Is the constructor still needed in React with autobinding and property initializers

后端 未结 3 1937
悲&欢浪女
悲&欢浪女 2021-02-05 17:39

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 lik

3条回答
  •  不要未来只要你来
    2021-02-05 18:15

    You don't need to define a constructor explicitly , and then do super(props).You can access the props as in the example below. i.e. '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(
           
    Hi
    ); } } ReactDOM.render( , mountNode);

提交回复
热议问题