React 中 Element、Component、Node、Instance 的区别
理解 React 中四个核心概念的含义和关系
问题
如何理解 React 中 Element、Component、Node、Instance 这四个概念?
解答
Element
Element 是 React 应用中最基本的构建块,是一个普通的 JavaScript 对象,用来描述 UI 的一部分。
// 原生 DOM 元素
const element = <div className="container">Hello</div>;
// 自定义组件元素
const element = <MyComponent name="React" />;
// 实际上是
const element = {
type: 'div',
props: {
className: 'container',
children: 'Hello'
}
};
Element 是不可变的,一旦创建就不能被修改。它只是告诉 React 想要在页面上渲染什么内容。
Component
Component 是由 Element 构成的可复用单元,可以是函数组件或类组件。
// 函数组件
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
// 类组件
class Welcome extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
Component 接收 props 作为输入,返回描述 UI 的 Element。
Node
Node 是 React 内部的虚拟节点,是 Element 的实例化表示。它包含了 Element 的所有信息,包括类型、属性、子节点等。
Node 是 React 用来描述 UI 的内部数据结构,最终会被渲染成真实的 DOM 元素。
Instance
Instance 是组件的实例,只存在于类组件中。每个类组件在应用中都有对应的 Instance。
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
increment = () => {
this.setState({ count: this.state.count + 1 });
}
render() {
return <button onClick={this.increment}>{this.state.count}</button>;
}
}
// 当组件被渲染时,React 会创建 Counter 的 Instance
// Instance 包含了 state、props 和方法
函数组件没有 Instance,因为它们只是纯函数。
关键点
- Element 是描述 UI 的不可变对象,是最基本的构建块
- Component 是可复用的 UI 单元,分为函数组件和类组件
- Node 是 React 内部的虚拟节点,用于构建虚拟 DOM 树
- Instance 只存在于类组件中,包含组件的状态和方法
- 函数组件没有 Instance,这也是它们更轻量的原因之一
目录