React Component 和 React Element 之间的区别
2022-08-30 04:58:43
React Component 和 React Element 之间有什么区别?文档提到了两者,但没有详细说明,有些方法需要组件,其他元素......
React Component 和 React Element 之间有什么区别?文档提到了两者,但没有详细说明,有些方法需要组件,其他元素......
这里涉及三种相关的东西,它们有自己的名字:
这有点令人惊讶,因为如果你习惯了其他UI框架,你可能会认为只有两种东西,大致对应于类(如)和实例(如)。在 React 中情况并非如此。组件实例与元素不是一回事,它们之间也没有一对一的关系。为了说明这一点,请考虑以下代码:Widget
new Widget()
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
class MyComponent extends React.Component {
constructor(props) {
super(props);
console.log('This is a component instance:', this);
}
render() {
const another_element = <div>Hello, World!</div>;
console.log('This is also an element:', another_element);
return another_element;
}
}
console.log('This is a component:', MyComponent)
const element = <MyComponent/>;
console.log('This is an element:', element);
ReactDOM.render(
element,
document.getElementById('root')
);
在上面的代码中:
MyComponent
(类本身)是一个组件element
是一个元素。它不是 的实例;相反,它只是对要创建的组件实例的描述。它是一个具有 、 和属性的对象。此处和 are 是一个空对象,并且是 。MyComponent
key
props
ref
type
key
ref
null
props
type
MyComponent
MyComponent
element
another_element
也是一个元素,并且具有 、 和属性,就像 do 一样 - 但这次的值是字符串 。key
ref
props
type
element
type
"div"
React 具有这三个不同概念的设计原因在 React 团队的博客文章 React Components, Elements, and Instances 中有详细的探讨,我建议阅读这篇文章。
最后,应该注意的是,虽然官方文档严格要求使用术语“组件”来指代函数或类,并使用“组件实例”来指代实例,但其他来源并不一定遵守这个术语;在 GitHub 上阅读 Stack Overflow 答案或讨论时,您应该会看到“组件”(错误地)用于表示“组件实例”。
为了进一步阐述答案,React Element没有任何方法,原型上也没有。这也使它们变得快速。
“ReactElement 是 DOM 元素的轻量级、无状态、不可变、虚拟表示” - React 术语表
react 组件函数返回后台 react 元素的 DOM 树(顺便说一句,这是虚拟 DOM)。涉及一些复杂的映射和差异逻辑,但基本上这些 React 元素映射到 DOM 元素。render()
您还可以直接创建一个元素,其中 arg 可以是 html 标记名称或 React 组件类。React.createElement(arg)