简体   繁体   English

从 JSX 渲染和从 function 渲染有什么区别?

[英]What is the difference between rendering from a JSX and from a function?

Consider the following:考虑以下:

const Foo = ({ bar }) => {
  return (
    <div>
      {bar}
    </div>
  )
}

What is the difference between <Foo bar='something' /> and Foo({ bar: 'something' }) ? <Foo bar='something' />Foo({ bar: 'something' })有什么区别?

render (
  <>
    {/* Is there any difference for the following two? */}
    <Foo bar='something' />
    {Foo({ bar: 'something' })}
  </>
);

When you call Foo({ bar: 'something' }) , and render the result in your component, then you are essentially no longer treating Foo as its own React component, and instead assimilating it into the calling component.当您调用Foo({ bar: 'something' })并在组件中渲染结果时,您实际上不再将Foo视为它自己的 React 组件,而是将其同化到调用组件中。 In effect, it would be the same as putting the result of calling the function inline in the parent component.实际上,这与将调用 function 的结果内联到父组件中相同。

On the other hand, when you use <Foo> in JSX syntax, or equivalently, React.createElement(Foo) , then Foo is treated as its own component, which means that it can make use of features like React Hooks.另一方面,当您在 JSX 语法中使用<Foo>或等效的React.createElement(Foo)时, Foo被视为自己的组件,这意味着它可以利用 React Hooks 等功能。

In the simplest case as you have shown, there is really no difference, but in practice, it generally makes sense to use the JSX syntax.在您展示的最简单的情况下,实际上没有区别,但在实践中,使用 JSX 语法通常是有意义的。

This expects the foo function is going to return an UI (eg Card, div).这期望 foo function 将返回一个 UI(例如 Card、div)。

<Foo bar ='something'/>

This does not expect the foo function to return an UI, ONLY RUN THE FUNCTION WITHIN IT.这并不期望 foo function 返回 UI,仅在其中运行 FUNCTION。

<Foo({bar:'something'})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM