Skip to content

组件的基本使用

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

  1. 函数式组件
  2. 类式组件

函数式组件

适用于简单组件的定义

执行流程:

  1. React解析组件标签
  2. 发现组件是使用函数定义的, 随后调用该函数, 将返回的虚拟DOM转为真实DOM, 随后呈现在页面中

注意

  1. 函数名必须大写
  2. 函数中必须有返回值
  3. render中必须写组件标签
  4. babel编译后开启了严格模式, 函数中的thisundefined
  • 代码示例
jsx
// 1. 创建函数式组件
function MyComponent() {
  console.log(this) // 此处的 this 是 undefined, 因为 babel 编译后开启了严格模式
  return <h2>用函数定义的组件, 适用于 [简单组件] 的定义</h2>
}
// 2. 渲染组件到页面
ReactDOM.render(<MyComponent />, document.getElementById("app"));

类式组件

适用于复杂组件的定义

使用之前先来复习一个类的基本知识

类的基本知识

  1. 类中的构造器不是必须写的, 要对实例进行一些初始化的操作, 比如添加指定属性时需要写
  2. 如果 B 类继承了 A 类, 且 B 类中写了构造器, 那么 B 类构造器中的super()是必须要调用的, 且super()必须在首行
  3. 类中所定义的方法, 都是放在了类的原型对象上, 供实例使用, 哪个实例调用方法, 方法中的this就指向哪个实例
  • 代码示例
js
// 创建一个 Person 类
class Person {
  // 构造器方法
  constructor(name, age) {
    // 构造器中的 this 是类的实例对象
    this.name = name
    this.age = age
  }

  /*
    一般方法, 在类的原型对象上, 供实例使用
    通过 Person 实例调用 speak 时, speak 中的 this 就是就是 Person 实例
    哪个实例调用 speak, this 就指向哪个实例
  */
  speak() {
    console.log(`我叫${this.name}, 今年${this.age}岁`)
  }
}

// 创建 Person 的实例对象
const p1 = new Person('Tom', 18)
console.log(p1)
const p2 = new Person('Jerry', 20)
console.log(p2)

p1.speak()
p2.speak()

// 创建一个 Student 类, 继承于 Person 类
class Student extends Person {
  // 当子类继承父类时, 如果子类需要 constructor 构造器, 必须调用 super() 方法
  constructor(name, age, grade) {
    // super 相当于所继承的父类构造器, 可以传递参数
    super(name, age)
    this.grade = grade
  }

  // 重写父类方法
  speak() {
    console.log(`我叫${this.name}, 今年${this.age}岁读${this.grade}`)
  }
}

// 创建 Student 的实例对象
const s1 = new Student('Miller', 18)
console.log(s1)
s1.speak()

const s2 = new Student('June', 21, '大一')
console.log(s2)

使用类式组件

类式组件执行流程:

  1. React解析组件标签, 找到了MyComponent组件
  2. 发现组件是使用类定义的, 随后new出来该类的实例, 并通过该实例调用原型上的render方法
  3. render返回的虚拟DOM转为真实DOM, 随后呈现在页面中
  • 代码示例
jsx
// 1. 创建类式组件
class MyComponent extends React.Component {
  // render 放在 MyComponent 的实例对象上, 供实例使用
  render() {
    // this 是 MyComponent 的实例对象 <=> MyComponent 组件实例对象
    console.log('render this:', this)
    return <h2>用类定义的组件, 适用于 [复杂组件] 的定义</h2>
  }
}

// 2. 渲染组件到页面
ReactDOM.render(<MyComponent />, document.getElementById("app"));

注意项

  1. 组件名必须首字母大写
  2. 虚拟DOM元素只能有一个根元素
  3. 虚拟DOM元素必须有结束标签