Is the call to super(props) in an ES6 class import

2020-03-01 10:22发布

Suppose I've the following class:

class Tabs extends React.Component {
  displayName: Tabs;

  static propTypes = {
  selected: React.PropTypes.number,
  children: React.PropTypes.oneOfType([
    React.PropTypes.array,
    React.PropTypes.element
  ]).isRequired
  };

  constructor() {
  super();
  this.state = {
    selected: 0,
    maxSelected: 0
  };

  render() {
    return(
      <div>
       {this.props.selected}
       {this.props.children}
      </div>
    );
  }
};

I want to know that if passing the following constructor is important:

constructor(props) {
  super(props);
}

My current code works just fine but I wanted to know if this is a good practice.

1条回答
叼着烟拽天下
2楼-- · 2020-03-01 11:08

According to Ben Alpert with the React team it's only necessary to pass props into the constructor if you intend on using this.props inside the constructor. After the constructor is invoked, React attaches the props to the component from the outside.

查看更多
登录 后发表回答