What is the difference between React Component and React Element? The documentation mentions both but does not go into detail, some methods require components, other elements...
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- How to toggle on Order in ReactJS
- void before promise syntax
- Keeping track of variable instances
There are three related kinds of thing involved here, with their own names:
This is slightly surprising, since if you're used to other UI frameworks you might expect that there'd only be two kinds of thing, roughly corresponding to classes (like
Widget
) and instances (likenew Widget()
). That's not the case in React; component instances are not the same thing as elements, nor is there a one-to-one relationship between them. To illustrate this, consider this code:In the code above:
MyComponent
(the class itself) is a Componentelement
is an Element. It's not an instance ofMyComponent
; rather, it's simply a description of the component instance to be created. It's an object withkey
,props
,ref
andtype
properties. Here,key
andref
arenull
,props
is an empty object, andtype
isMyComponent
.MyComponent
gets created (and, in the example above, logs itself from its constructor) whenelement
gets rendered.another_element
is also an element, and haskey
,ref
,props
andtype
properties just likeelement
does - but this time the value oftype
is the string"div"
.The design reasons why React has these three distinct concepts are explored in detail in the React team's blog post React Components, Elements, and Instances, which I recommend reading.
Finally, it should be noted that while the official docs are rigorous about using the term "component" to refer to a function or class and "component instance" to refer to an instance, other sources do not necessarily adhere to this terminology; you should expect to see "component" used (incorrectly) to mean "component instance" when reading Stack Overflow answers or discussions on GitHub.
A component is a factory for creating elements.
React components are mutable while elements are not
React Element
- It is a simple object that describes a DOM node and its attributes or properties you can say. It is an immutable description object and you can not apply any methods on it.Eg -
React Component
- It is a function or class that accepts an input and returns a React element. It has to keep references to its DOM nodes and to the instances of the child components.Elements are thunks.
React lets you define UIs as pure functions defined on application state. It could implement this by computing the entire UI during each state change, but this would be expensive. Elements are computational descriptions (thunks), and if they don't change, and you're using
PureComponent
s, React won't bother recomputing that subtree.