Difference between React Component and React Element

前端 未结 11 1947
栀梦
栀梦 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:39

    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. The object representation of React element would be as follows,

    const element = React.createElement(
      'div',
      {id: 'login-btn'},
      'Login'
    )
    

    The above createElement returns as object as below,

    {
      type: 'div',
      props: {
        children: 'Login',
        id: 'login-btn'
      }
    }
    

    And finally it renders to the DOM using ReactDOM.render as below,

    Login

    Whereas a 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. JSX transpiled as createElement at the end.

    function Button ({ onLogin }) {
      return React.createElement(
        'div',
        {id: 'login-btn', onClick: onLogin},
        'Login'
      )
    }
    

提交回复
热议问题