Skip to content
Go back

读《How Does React Tell a Class from a Function?》

Table of contents

Open Table of contents

React 为什么要区别对待类和函数组件?

const result = Greeting(props); // <p>Greeting</p>

const instance = new Greeting(props);
const result = instance.render(); // <p>Greeting</p>

如果类组件没有实例化会怎样?

能否给所有组件统一使用 new 调用?

结论:

React 是如何区别类和函数组件的?

React 依靠在基类 Component 的 prototype 上添加 isReactComponent 属性,实现对类组件和函数组件的区分:

class Component {}
Component.prototype.isReactComponent = {};

class Greeting extends Component {}
const isClassComponent = !!Greeting.prototype.isReactComponent; // true

补充说明

为什么不这样做?

  1. 不用 instanceof 检查 Component,是因为:

    • 当项目存在多个 React 版本(比如微前端或依赖冲突场景),不同 React 版本的 Component 构造函数不是同一个引用,导致 instanceof 判断失效,不能可靠区分类组件。
  2. 也不用检查 render 方法等属性,因为:

    • render 属于实例方法,不一定能直接在 prototype 上检测到。
    • 未来 React API 可能演化,不能保证类组件总有 render 方法。
    • 实现上“少查一项”就是在性能、健壮性层面的加分。

基础知识

原型链

function Person() {}
Person.prototype.getName = function () {};

const person = new Person();
console.log(person.__proto__ === Person.prototype); // true

Share this post on:

Previous Post
读《Why Do React Elements Have a $$typeof Property?》
Next Post
读《Why Do We Write super(props)?》