将代码保存在渲染函数之外与保留代码的回报

发布于 2025-02-13 00:03:15 字数 444 浏览 2 评论 0原文

我想知道,如果我们只有一些条件渲染,我们是否应该选择第二种方法:

第一方法:

const MyComponent = ({ isOpen }) => {
...
return (
   {isOpen && <MyAnotherComponent />}
);
}

第二种方法:

const MyComponent = ({ isOpen }) => {
   ...
   const renderComponent = () => {
       if (isOpen) {
       return <MyAnotherComponent />
       }
       
   }

   return (
      renderComponent()
   )
};

I'd like to know whether we should go for 2nd approach if we just have a few conditional rendering:

1st Approach:

const MyComponent = ({ isOpen }) => {
...
return (
   {isOpen && <MyAnotherComponent />}
);
}

2nd Approach:

const MyComponent = ({ isOpen }) => {
   ...
   const renderComponent = () => {
       if (isOpen) {
       return <MyAnotherComponent />
       }
       
   }

   return (
      renderComponent()
   )
};

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

情场扛把子 2025-02-20 00:03:15

条件在哪里?最好遵循第一个方法,这将使所有内容都作为组件回报而不是函数调用。您可以将组件存储为变量,然后根据条件渲染该变量。
您可以在 jsx 中使用条件与三元操作员或短路条件&amp;&amp; &lt; component/&gt;,您还可以在 jsx 中使用map和其他类似的方法, jsx 将返回组件

只是在返回作为组件。我个人从未遇到任何使用功能调用的代码或项目。

Where are conditions? And it's better you follow 1st approach which will keep everything as a component in return and not a function call. You can store you component as a variable and then render that variable based on condition.
You can use condition in JSX with ternary operator or short-circuiting condition && <Component/> and you can also use map and other similar approach within JSX which will return component

Just don't use function calls within return as a component. I personally never encountered any code or project which uses function call.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文