将代码保存在渲染函数之外与保留代码的回报
我想知道,如果我们只有一些条件渲染,我们是否应该选择第二种方法:
第一方法:
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
条件在哪里?最好遵循第一个方法,这将使所有内容都作为组件回报而不是函数调用。您可以将组件存储为变量,然后根据条件渲染该变量。
您可以在 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 usemap
and other similar approach within JSX which will return componentJust don't use function calls within
return
as a component. I personally never encountered any code or project which uses function call.