React Components, Elements, and Instances

发布时间 2023-05-26 16:40:55作者: saaspeter

see: https://legacy.reactjs.org/blog/2015/12/18/react-components-elements-and-instances.html

https://www.robinwieruch.de/react-element-component/

https://stackoverflow.com/questions/30971395/difference-between-react-component-and-react-element

这里摘抄一下第一个blog的summary:

Summary 

An element is a plain object describing what you want to appear on the screen in terms of the DOM nodes or other components. Elements can contain other elements in their props. Creating a React element is cheap. Once an element is created, it is never mutated.

component can be declared in several different ways. It can be a class with a render()method. Alternatively, in simple cases, it can be defined as a function. In either case, it takes props as an input, and returns an element tree as the output.

When a component receives some props as an input, it is because a particular parent component returned an element with its type and these props. This is why people say that the props flows one way in React: from parents to children.

An instance is what you refer to as this in the component class you write. It is useful for storing local state and reacting to the lifecycle events.

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.

Finally, to create elements, use React.createElement()JSX, or an element factory helper. Don’t write elements as plain objects in the real code—just know that they are plain objects under the hood.