React in the constructor constractor, why use super (props)

Foreword

  Last night the company will be organized to share front-end, when he spoke React Class methods, some students asked why the constructor must be super, I remember before watching the video inside the dark horse mentioned, the ability to turn it on

content

React official Chinese documents there are something like this:

In React, we can also be achieved by a combination of this. "Special" component can customize and render the "General" component by props. Also applies to the combination of the component (defined in the form of class https://react.docschina.org/docs/composition-vs-inheritance.html ).

function Dialog(props) {
  return (
    <FancyBorder color="blue">
      <h1 className="Dialog-title">
        {props.title}
      </h1>
      <p className="Dialog-message">
        {props.message}
      </p>
      {props.children}
    </FancyBorder>
  );
}

class SignUpDialog extends React.Component {
  constructor(props) {
    super(props);
    this.handleChange = this.handleChange.bind(this);
    this.handleSignUp = this.handleSignUp.bind(this);
    this.state = {login: ''};
  }

  render() {
    return (
      <Dialog title="Mars Exploration Program"
              message="How should we refer to you?">
        <input value={this.state.login}
               onChange={this.handleChange} />

        <button onClick={this.handleSignUp}>
          Sign Me Up!
        </button>
      </Dialog>
    );
  }

  handleChange(e) {
    this.setState({login: e.target.value});
  }

  handleSignUp() {
    alert(`Welcome aboard, ${this.state.login}!`);
  }
}

 1. First without super will be reported the following error

 super error

 

 2. Why will complain? Why incoming props

 

 

it means:

  • If extends through the inherited constructor which must be super, this is the rules of grammar, not on the error.
  • super is a function that is the parent class constructor, with super, is in reference to the parent class constructor
  • If you do not pass props, constructors below which will become undefined references

 

Guess you like

Origin www.cnblogs.com/rong88/p/11948880.html