什么时候传递道具给super()很重要,为什么?

class MyComponent extends React.Component {
  constructor(props) {
    super(); // or super(props) ?
  }
}

当前回答

对于react 16.6.3版本,我们使用super(props)来初始化状态元素名称:this.props.name

constructor(props){
    super(props);        
}
state = {
  name:this.props.name 
    //otherwise not defined
};

其他回答

对于react 16.6.3版本,我们使用super(props)来初始化状态元素名称:this.props.name

constructor(props){
    super(props);        
}
state = {
  name:this.props.name 
    //otherwise not defined
};

这是我做的小提琴:jsfiddle.net。它表明默认情况下道具不是在构造函数中分配的。据我所知,它们是在方法React.createElement中分配的。因此,super(props)应该只在超类的构造函数手动将props赋给this.props时调用。如果你只是扩展React。组件调用super(props)不会对props做任何事情。也许它会在React的下一个版本中被改变。

当你把道具传递给super时,道具被分配给this。看看下面的场景:

constructor(props) {
    super();
    console.log(this.props) //undefined
}

当你这样做的时候:

constructor(props) {
    super(props);
    console.log(this.props) //props will get logged.
}

按照源代码

function ReactComponent(props, context) {
  this.props = props;
  this.context = context;
}

你每次有道具的时候都要传递道具,不要把道具放到这里。手动道具。

Super()用于调用父构造函数。

Super (props)将把道具传递给父构造函数。

从你的例子中,super(props)会调用React。组件构造函数将props作为参数传入。

更多关于super的信息: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/super