其他分享
首页 > 其他分享> > React中构造函数constractor,为什么要用super(props)

React中构造函数constractor,为什么要用super(props)

作者:互联网

前言

  昨天晚上公司组织了前端分享会,在讲到React Class方法的时候,有的同学提出,为什么构造函数一定要super,我记得我之前看的黑马视频里面有讲过,就再翻出来

内容

React官方中文文档里面有这样的内容:

在 React 中,我们也可以通过组合来实现这一点。“特殊”组件可以通过 props 定制并渲染“一般”组件。组合也同样适用于以 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.首先不加super会报以下错误

 super报错

 

 2.为什么会报错?为什么要传入props

 

 

意思就是:

 

标签:React,constractor,props,handleChange,super,login,构造函数
来源: https://www.cnblogs.com/rong88/p/11948880.html