如何理解react中的super() super(props)

class WebSite extends React.Component {
  constructor() {
      super();

      this.state = {
        name: "菜鸟教程",
        site: "https://www.runoob.com"
      }
    }
  render() {
    return (
      <div>
        <Name name={this.state.name}/>
        <Link site={this.state.site} />
      </div>
    );
  }
}

class Name extends React.Component {
  constructor(props) {
     super(props)
     console.log(this.props)  // 若是使用super() 这里输出undefined
  }
  render() {
    return (
      <h1>{this.props.name}</h1>
    );
  }
}
 
class Link extends React.Component {
  render() {
    return (
      <a href={this.props.site}> // 使用了super能够this.props获取传入的参数 未使用报错
        {this.props.site}
      </a>
    );
  }
}
 
ReactDOM.render(
  <WebSite />,
  document.getElementById('example')
);
</script>

</body>
</html>

  子类继承父类的属性:须要使用super()继续父类的属性,同时建立this(子类自己没有this);html

      若是子组件中没有constructor没有显式定义。会默认天机constructor super()函数

 

 

super(props)的做用就是在父类的构造函数中给props赋值一个对象this.props=props这样就能在它的下面定义你要用到的属性了,然而其余的因为没有传参就直接赋值为undefindthis

 

因为state下面没有属性,因此若是只是定义state就能够直接super()spa

相关文章
相关标签/搜索