ES6类中的超级(道具)呼叫是否重要? [英] Is the call to super(props) in an ES6 class important?

查看:101
本文介绍了ES6类中的超级(道具)呼叫是否重要?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下类:

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.

推荐答案

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

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.

这篇关于ES6类中的超级(道具)呼叫是否重要?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆