React 中的 Component / Element / Instance

883 阅读2分钟

其实这是个特别无聊的问题,但是依然会有很多人会问。虽然我也经常分不清这些概念之间的区别,但是还是写一下吧。

react-components-elements-and-instances

官网里的这篇文章是 Dan 写的,里面其实除了写他们之间的区别之外,还写了一些其他比较有意义的内容,所以还是推荐看一下。我这里就是把文章的内容总结一下,放在这里。

Component 就是指 class component 或者 function component,也就是我们经常写的 react 组件。

Element 其实指的是 Component 的返回值,就是一个 javascript 的对象(虚拟 dom 对象?)。也就是我们经常说的 dom 的描述对象。只不过呢 element 分为两种情况,一种是 html 中默认就有的元素,就是 DOM element,一种是组件元素,就是 component element。

(DOM Element)When an element’s type is a string, it represents a DOM node with that tag name, and props correspond to its attributes.

(Component Element)However, the type of an element can also be a function or a class corresponding to a React component.

例如:

const element1 = {
  type: 'button', // 这里是个 string,表示 html 中默认有的元素类型
  props: {
    className: 'btn',
    children: []
  }
}

const element2 = {
  type: Button, // 注意,这里是一个 component
  props: {
    size: 'sm',
    type: 'danger'
  }
}

Instance 指的就是 class component 的实例化内容,其实就是我们在 class component 中的 this。引用文章中的一段话:

An instance is what you refer to as this in the component class you write. Function components don’t have instances at all. Class components have instances, but you never need to create a component instance directly—React takes care of this.

其他

这篇文章中除了上述内容之外,还有一些营养可以吸收。

This is a part of the process that React calls reconciliation which starts when you call ReactDOM.render() or setState(). By the end of the reconciliation, React knows the resulting DOM tree, and a renderer like react-dom or react-native applies the minimal set of changes necessary to update the DOM nodes (or the platform-specific views in case of React Native).

这里说了 reconciliation 的起点,和内容。

This gradual refining process is also the reason React apps are easy to optimize. If some parts of your component tree become too large for React to visit efficiently, you can tell it to skip this “refining” and diffing certain parts of the tree if the relevant props have not changed. It is very fast to calculate whether the props have changed if they are immutable, so React and immutability work great together, and can provide great optimizations with the minimal effort.

这段话说明了为什么要用 immutable 的内容。

github.com/facebook/re…

这部分内容说了为什么 element 的 type 需要用特殊标记。