React Components, Elements, and Instances

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.

 

关于用JSX来定义component或element,以下是我问Bot得到的答复:

问:请用JSX语法来定义一个react element

答:

const element = (
  <div>
    <h1>Hello, world!</h1>
    <p>Welcome to my React app.</p>
  </div>
);

问:那再用JSX定义一个component

import React from 'react';

const MyComponent = (props) => {
  return (
    <div>
      <h1>Hello, {props.name}!</h1>
      <p>{props.description}</p>
    </div>
  );
}

export default MyComponent;

答:准确来说,如果使用箭头函数,并且返回一个React元素(React element),那么它就是一个无状态函数式组件(Stateless Functional Component)。这种类型的组件通常只是简单地渲染UI,不需要维护自己的状态或进行复杂的操作。这种组件通常以函数的形式定义,而不是类的形式。

如果在函数中返回JSX元素,那么它就是一个React元素(React element)。React元素是由React组件返回的简单JavaScript对象,它描述了一个DOM节点的类型,属性和子节点。当React元素被渲染时,它会被转换为实际的DOM节点。因此,React元素是React应用程序中构建UI的基本构建块。

 

posted @ 2023-05-26 16:35  saaspeter  阅读(10)  评论(0编辑  收藏  举报