ES6课程中对超级(道具)的调用是否重要?

Nir*_*osh 10 ecmascript-6 reactjs

假设我有以下课程:

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>
    );
  }
};
Run Code Online (Sandbox Code Playgroud)

我想知道如果传递以下构造函数很重要:

constructor(props) {
  super(props);
}
Run Code Online (Sandbox Code Playgroud)

我目前的代码工作得很好,但我想知道这是不是一个好习惯.

Ric*_*yon 17

根据Ben Alpert和React团队的说法,如果你打算在this.props构造函数中使用,只需要将props传递给构造函数.在调用构造函数之后,React将props从外部附加到组件.

  • @usama super(props) 在构造函数中是不必要的,除非你要在构造函数级别做一些工作。在 ES2015 中,每个类都有默认构造函数,因此没有必要有空的构造函数。 (3认同)