What's the difference between “super()” and “super(props)” in React when using es6 classes?

后端 未结 10 1954
不思量自难忘°
不思量自难忘° 2020-11-22 09:01

When is it important to pass props to super(), and why?

class MyComponent extends React.Component {
  constructor(props) {
    supe         


        
相关标签:
10条回答
  • 2020-11-22 09:30

    Here is the fiddle I've made:jsfiddle.net. It shows that props are assigned not in the constructor by default. As I understand they are assinged in the method React.createElement. Hence super(props) should be called only when the superclass's constructor manually assings props to this.props. If you just extend the React.Component calling super(props) will do nothing with props. Maybe It will be changed in the next versions of React.

    0 讨论(0)
  • 2020-11-22 09:40

    As per source code

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

    you must pass props every time you have props and you don't put them into this.props manually.

    0 讨论(0)
  • 2020-11-22 09:41

    For react version 16.6.3, we use super(props) to initialize state element name : this.props.name

    constructor(props){
        super(props);        
    }
    state = {
      name:this.props.name 
        //otherwise not defined
    };
    
    0 讨论(0)
  • 2020-11-22 09:44

    Dan Abramov wrote an article on this topic:

    Why Do We Write super(props)?

    And the gist of it is that it's helpful to have a habit of passing it to avoid this scenario, that honestly, I don't see it unlikely to happen:

    // Inside React
    class Component {
      constructor(props) {
        this.props = props;
        // ...
      }
    }
    
    // Inside your code
    class Button extends React.Component {
      constructor(props) {
        super(); //                                                                     
    0 讨论(0)
提交回复
热议问题