二、React学习笔记整理(组件)

121 阅读2分钟

组件

组件定义:⽤来实现局部功能效果的代码和资源的集合(html/css/js/image等等)。
组件作用:复⽤编码, 简化项⽬编码, 提⾼运⾏效率。

React提供了两种创建组件的⽅式:

  • 函数式组件
  • 类式组件

函数式组件

// 1. 创建函数式组件
function MyComponent(props) {
// 函数式组件会默认接收一个props参数,包含该组件的属性以及事件
    console.log(this) // undefined babel 编译后开启了严格模式, this不能指向window, 就是undefined
    return <h2>我是用函数定义的组件(适用于简单组件的定义)</h2>
}
// 2. 渲染组件到页面
ReactDOM.render(<MyComponent />, document.getElementById('test'))
执行了 ReactDOM.render()... 之后, 发生了什么
1. React解析组件标签, 找到了MyComponent组件
2. 发现组件是使用函数定义的, 随后调用该函数, 将返回的虚拟DOM转
为真实DOM, 随后呈现在页面中

类式组件

// 1.创建类式组件
class MyComponent extends React.Component{
  // render放在MyComponent类的原型对象上,供实例调用
  // render中的this是 MyComponent的实例对象
  render(){
    console.log(this);
    return (
      <h2>我是用类定义的组件,适用于比较复杂的组件定义</h2>
    )
  }
}
// 2.渲染组件
ReactDOM.render(<MyComponent />, document.getElementById('test'))
执行 ReactDOM.render之后发生了什么
 1.React解析组件标签,找到MyComponent组件
 2.发现组件是类定义的,随后new出来该类的实例
 3.通过该实例调用原型上的render方法,将render返回的虚拟DOM转换为真实DOM,渲染出来
 

复习类相关知识

// 创建一个Person类
class Person{
    // 构造器
    constructor(name, age){
      this.name =  name
      this.age = age
    }
  /**
   类的方法在类的原型对象(Prototype)上,供实例来调用
   通过Person实例调用speak时,speak中的this就是Person的实例
   */
   // 一般方法
    speak(){
      console.log('我的名字是'+this.name+',我的年龄是'+this.age)
    }
}

let p1 = new Person('jack', 17);
let p2 = new Person('tom', 18);
console.log(p1);
console.log(p2);
p1.speak();
p2.speak()

// 创建一个Student类, 继承Person类
class Student extends Person{
    constructor(name, age, grade){
      // 子类重写父类构造方法,必须用super()
      super(name, age)
      this.grade = grade;
    }
  speak(){
    console.log('我的名字是'+this.name+',我的年龄是'+this.age+',我的成绩是'+this.grade)
  }
}
let stu1 = new Student('张三', 18);
let stu2 = new Student('王五', 19, 120);
console.log(stu1);
console.log(stu2);
stu1.speak();// 如果Student原型对象上没有, 就会从原型链上继续找
stu2.speak();

总结:

  1. 类中的构造方法不是必须写的,要对实例进行初始化操作时才写
  2. 如果B类继承A类,且A类中写了构造器,B类构造器必须写super()
  3. 类中定义的方法,都是放在类的原型对象上,,供实例使用
  4. 在继承中,如果子类使用的方法在没有子类原型对象上找到,就会通过原型链继续向父级查找