简体   繁体   中英

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' }) ?

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. In effect, it would be the same as putting the result of calling the function inline in the parent component.

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.

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.

This expects the foo function is going to return an UI (eg Card, div).

<Foo bar ='something'/>

This does not expect the foo function to return an UI, ONLY RUN THE FUNCTION WITHIN IT.

<Foo({bar:'something'})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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