如何理解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);

      如果子组件中没有constructor没有显式定义。会默认天机constructor super()

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

由于state下面没有属性,所以如果只是定义state就可以直接super()

转载于:https://www.cnblogs.com/huancheng/p/11095832.html

猜你喜欢

转载自blog.csdn.net/weixin_34253126/article/details/94278578