ReactJs - 条件渲染或隐藏组件 [英] ReactJs - Conditional Rendering or hiding component
问题描述
在条件渲染或使用 { display: 'none' }
隐藏组件之间进行选择的实际方法是什么?
What's the de facto approach to choosing between conditional rendering or hiding the component with { display: 'none' }
?
为了便于讨论,假设我有一个 FilterComponent
保存过滤器的 title
和一个 FilterItems
列表, 带有 name
和 amount
.
For the sake of discussion, let's say that I have a FilterComponent
that holds the title
of the filter, and a list of FilterItems
, with name
and amount
.
简而言之,FilterComponent
可以是:
颜色
蓝色 (19)
Blue (19)
黄色 (17)
橙色 (3)
黑色 (7)
绿色 (10)
+ 显示更多
当点击Show More
按钮时,会显示更多的FilterItem
,即
When hitting Show More
button, more FilterItem
s will be displayed, i.e.
颜色
蓝色 (19)
Blue (19)
黄色 (17)
橙色 (3)
黑色 (7)
绿色 (10)
棕色 (17)
粉红色 (88)
白色 (55)
红色 (32)
紫色 (17)
- 显示更少
我应该隐藏 Show More
下方的 FilterItem
吗?或者我应该为下面的那些返回 null 并在使用 Show More
更新状态后呈现它们?
Should I hide the FilterItem
s that are below the Show More
? Or should I return null for those below and render them after updating the state with Show More
?
推荐答案
我认为有几种方法可以满足您的需求.然而,这似乎是最常用的:
I think there are a few ways to accomplish what you need. However, this seems to be the most practised:
{myConditionIsTrue && <MyComponent />}
在您的情况下,使用 state 是有意义的.我会在 FilterComponent 中有一个名为 showFullList
In your case, it makes sense to use state. I would have a prop inside FilterComponent called showFullList
{this.state.showFullList && (
<React.Fragment>
<All/><The/><Other/><Components/>
</React.Fragment>)}
请注意,这种机制实际上是在 DOM 中删除/添加内容.
Just be weary, this mechanism is actually removing/adding to the DOM.
这篇关于ReactJs - 条件渲染或隐藏组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!