美文网首页
基于类创建react组件

基于类创建react组件

作者: 转移到CSDN名字丹丹的小跟班 | 来源:发表于2021-01-29 15:56 被阅读0次
    class Dislog extends React.Component {
    static defaultProps = {}  //设置属性默认值(从父组件传递过来的属性)
      constructor (props, context, updater) {
        // es6继承里,一旦使用了constructor,在第一行的位置必须执行super()方法。
        // 相当于React.Component.call(this),也就是call继承,把父类的私有属性继承过来 。
        super()
        // 继承过来的私有属性
        // this.props 属性集合
        // this.refs  ref集合
        // this.context  上下文
        // this.updater
        // 当super里面没有传参时,this.props为undefined
        console.log(props)    //{title: {name: "fjl"}}
        console.log(this.props)  //undefined
      }
      render() {
        // 不管super与constructor里面有没有参数,在render里面都可以拿到props参数。props属性是只读属性,不能更改。
        console.log(this.props)
        return <section>
          <h3>系统提示</h3>
          <div>内容</div>
        </section>
      }
    }
    
    // 基于类继承创建组件时,首先基于creatElement把jsx转换为一个对象,当render函数渲染对象时,遇到type是一个
    // 函数或者是一个类不是直接创建元素,而是先把这个函数执行
    // (1.如果是函数式声明的组件,就把他当作普通方法直接执行, 把返回的jsx元素进行渲染)
    //  (2.如果是类声明的组件,会把当前类new执行,创建类的一个实例[当前本次调取的组件就是他的实例],执行完后constructor后,
    // 就会执行this.render()方法,把render返回的jsx拿过来进行渲染)
    // 不管那一种方式,都会将props作为参数给方法或类
    ReactDOM.render(<div>
      <Dislog title={{name: 'fjl'}}></Dislog>
    </div>, document.getElementById("root"))
    

    相关文章

      网友评论

          本文标题:基于类创建react组件

          本文链接:https://www.haomeiwen.com/subject/xsdkzktx.html