Difference between React Component and React Element

前端 未结 11 1949
栀梦
栀梦 2020-12-02 07:29

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 element

11条回答
  •  心在旅途
    2020-12-02 07:50

    React Elements

    A React Element is just a plain old JavaScript Object without own methods. It has essentially four properties:

    • type, a String representing an HTML tag or a reference referring to a React Component
    • key, a String to uniquely identify an React Element
    • ref, a reference to access either the underlying DOM node or React Component Instance)
    • props (properties Object)

    A React Element is not an instance of a React Component. It is just a simplified "description" of how the React Component Instance (or depending on the type an HTML tag) to be created should look like.

    A React Element that describes a React Component doesn't know to which DOM node it is eventually rendered - this association is abstracted and will be resolved while rendering.

    React Elements may contain child elements and thus are capable of forming element trees, which represent the Virtual DOM tree.

    React Components and React Component Instances

    A custom React Component is either created by React.createClass or by extending React.Component (ES2015). If a React Component is instantiated it expects a props Object and returns an instance, which is referred to as a React Component Instance.

    A React Component can contain state and has access to the React Lifecycle methods. It must have at least a render method, which returns a React Element(-tree) when invoked. Please note that you never construct React Component Instances yourself but let React create it for you.

提交回复
热议问题