React 之 面向组件编程

什么是组件?

用来实现局部功能效果的代码和资源的集合(html/css/image等等)

 

为什么要使用组件?

作用:复用编码,简化项目编程,提高运行效率

 

官方提供了两种定义组件的方式

1.函数式组件

特点:适用于[简单组件]的定义

 

一.函数式组件

// 创建函数式组件
    function MyComponent(){
      console.log(this) // 此处的this是undefined 因为babel编译后开启了严格模式
      return <h2>我是函数定义的组件</h2>
    }
    ReactDOM.render(<MyComponent/>,document.getElementById('test'))
    /* 
       执行了ReactDOM.render后发生了什么?
       1.React解析组件标签,找到了MyComponent组件
       2.发现组件是使用函数定义的,随后调用该函数,将返回的虚拟dom转为真实的dom,随后呈现在页面中

    */

 

二.类式组件

 class MyComponent extends React.Component {
      render(){
        /* 
           render是放在哪里的? --MyComponent的原型对象上,供实例使用 
           render中的this是谁? --MyComponent的实例对象,也可以说MyComponent组件实例对象 = 组件对象
        */
        console.log('render中的this:',this)
        return <h2>我是用类定义的组件(适用于[复杂组件]的定义)</h2>
      }
    }
    // 2.渲染到页面
    ReactDOM.render(<MyComponent/>,document.getElementById('test'))
    /* 
       执行了ReactDOM.render(<MyComponent/>.....)后发生了什么?
       1.React解析组件标签,找到MyComponent组件
       2.发现组件是使用类定义的,随后new出来类的实例,并通过实例去调用render方法
    */

 

 

类的复习

class Person {
        // 构造器方法
        constructor(name,age){
          //构造器中的this是谁? 类的实例对象
          this.name= name
          this.age = age
        }
        // speak方法放在了哪里? Person类的原型对象上,供实例使用
        speak(){
          console.log(`我叫${this.name}, 我的年龄是${this.age}`);
        }
      }
      const p1 = new Person('tom',18)
      p1.speak()
      console.log(p1);
    
    
      class Student extends Person {
        constructor(name,age,grande){
          super(name,age) //必须在第一行
          this.grande = grande
        }
        //重写从父类继承过来的方法
        speak(){
          console.log(`我叫${this.name}, 我的年龄是${this.age},我的年级是${this.grande}`);
        }
      }

      const s1 =  new Student('小行',30,'一年级')
      s1.speak()
      console.log(s1)

总结:
1.类中的构造器不是必须要写的,要对实例进行一些初始的从操作,如添加指定属性时才写
2.如果A类继承了B类,且A类中写了构造器,那么A类构造器中的super是必须要调用的
3.类中所定义的方法,都是放在了类的原型对象上,供实例去使用

 

posted @ 2021-04-06 20:47  zmztyas  阅读(61)  评论(0编辑  收藏  举报