zoukankan      html  css  js  c++  java
  • 如何理解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()

  • 相关阅读:
    设计模式-状态模式(25)
    设计模式-访问者模式(24)
    设计模式-观察者模式(22)
    设计模式-中介者模式(21)
    设计模式-行为型模式小结(20)
    设计模式-迭代器模式(19)
    Tomcat安装
    MySQL单表查询
    MySQL表操作
    MySQL表的完整性约束
  • 原文地址:https://www.cnblogs.com/huancheng/p/11095832.html
Copyright © 2011-2022 走看看