简体   繁体   English

在 React 中使用“&&”有条件地渲染组件是一种不好的做法吗?

[英]Is it a bad practice to conditionally render a component with "&&" in React?

In other words, is this:换句话说,是这样的:

const [condition, setCondition] = useState(true);

return (
   condition && <Component /> 
)

As good as this:就像这样:

const [condition, setCondition] = useState(true);

return (
   condition ? <Component /> : null
)

In terms of bugs, rendering, etc.?在错误,渲染等方面? Because I'm sure that using && to condition something like that in vanilla JavaScript is not recommended.因为我确定不建议在香草 JavaScript 中使用&&来调节类似的东西。

Thanks!谢谢!

Simply it depends, if the <Component /> is a very large component with a lot of content and you toggle a lot, it would be better to display: none than completely destroy it.简单来说,如果<Component />是一个包含很多内容的非常大的组件并且您切换了很多,那么最好display: none ,而不是完全销毁它。

For example例如

<Component style={{ display: condition && 'unset' : 'none' }} /> 

Keep in mind, that the style here will be a prop that needs to pass to the root element of the component .请记住,这里的style将是一个需要传递给component根元素的道具。

but if it's a small component, destroying and re-initializing it will not be a bad practice.但如果它是一个小组件,销毁并重新初始化它不会是一个坏习惯。

No, it's not a bad practice;不,这不是一个坏习惯。

these two snippets will behave exactly the same: no difference at all.这两个片段的行为完全相同:完全没有区别。

condition && <Component /> 
condition ? <Component /> : null 

why?为什么? in both case the output is a valid react child :在这两种情况下 output 都是有效的反应子

type ReactNode = ReactElement | string | number | ReactFragment | ReactPortal | boolean | null | undefined;

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

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