简体   繁体   中英

Call a functional component in React before it is declared

const ShowHide = () => {
   return <Item/>;
};

const Item = () => {
   return(
     //few lines of code
   );
};

Here, the functional component ShowHide calls component 'Item'. Item is an arrow function and it is not hoisted.

How is it possible to call Item before it is declared?

How is it possible to call Item before it is declared?

It's imposible. Read this: javascript variables and temporal dead zone

You can define Item in other file, and imports to file with ShowHide component. It's all what you can do.

Pretty much what ASDFGerte commented.

The following would not work:

 const ShowHide = () => { return Item(); }; console.log(ShowHide()); const Item = () => { return 'hello world' };

Because you are trying to use a const before it's defined and as you can see it won't be hoisted.

The following will work:

 const ShowHide = () => { return Item(); }; const Item = () => { return 'hello world' }; console.log(ShowHide());

Because by the time ShowHide is called and Item is needed it is already defined.

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