【问题标题】:ReactJs - Conditional Rendering or hiding componentReactJs - 条件渲染或隐藏组件
【发布时间】:2019-04-25 05:29:08
【问题描述】:

在条件渲染或使用{ display: 'none' } 隐藏组件之间进行选择的实际方法是什么?

为了便于讨论,假设我有一个FilterComponent,其中包含过滤器的title,以及一个FilterItems 列表,其中包含nameamount

简而言之,FilterComponent 可以是:

颜色

  • 蓝色 (19)

  • 黄色 (17)

  • 橙色 (3)

  • 黑色 (7)

  • 绿色 (10)

    + Show More

点击Show More按钮时,会显示更多FilterItems,即

颜色

  • 蓝色 (19)

  • 黄色 (17)

  • 橙色 (3)

  • 黑色 (7)

  • 绿色 (10)

  • 棕色 (17)

  • 粉色 (88)

  • 白色 (55)

  • 红色 (32)

  • 紫色 (17)

    - Show Less

我应该隐藏Show More 下方的FilterItems 吗?或者我应该为下面的那些返回 null 并在使用 Show More 更新状态后渲染它们?

【问题讨论】:

    标签: reactjs conditional-rendering


    【解决方案1】:

    我认为有几种方法可以满足您的需求。但是,这似乎是最实用的:

    {myConditionIsTrue && <MyComponent />}
    

    在您的情况下,使用状态是有意义的。我会在 FilterComponent 中有一个名为 showFullList

    的道具
    {this.state.showFullList && (
     <React.Fragment>
       <All/><The/><Other/><Components/>
    </React.Fragment>)}
    

    请放心,这种机制实际上是在移除/添加到 DOM。

    【讨论】:

      【解决方案2】:

      通常在 React 中,最好不渲染某些东西而不是将其渲染为隐藏。这是一个相关的讨论: https://discuss.reactjs.org/t/conditional-rendering-or-toggling-hidden-classes/2535/6

      【讨论】:

        【解决方案3】:

        我会选择“更新状态”的方法。这样,您始终拥有该状态中显示的实际 filterItems。因此,您的组件状态是同步的,并代表当前正在显示的 UI。

        猜猜这个问题没有对错=)

        【讨论】:

          【解决方案4】:

          在单击“显示更多”并且状态已更新之前不渲染不应显示的项目会更有意义。通过这种方式,您可以在单击Show More 之前处理默认情况下应显示多少项目。通过这种方式,您可以对所有 FilterItems 使用完全相同的逻辑,而不是对某些元素应用内联样式或特殊类,但只渲染其中的 X

          【讨论】:

            【解决方案5】:

            您可以更改 isHidden 或类似的初始状态值。当您单击按钮时,值将与之前的情况相反。当你想渲染时,你应该给出条件;

            { isHidden &&
            
            ...
            

            【讨论】:

              【解决方案6】:

              一般来说,display: none 和条件渲染之间没有显着的性能差异,因为两种情况下浏览器的行为几乎相同。主要区别在于,如果您使用display: none,则节点不会从 DOM 树中删除,这会迫使一些 CSS 伪选择器(如 :last-child)将隐藏节点视为最后一个子节点,依此类推。因此,它与性能无关,而主要与 CSS 相关。我想这两种方法都可以使用:)

              【讨论】:

                【解决方案7】:

                我比较喜欢两种方法:

                #1 元素变量

                const button = <LogoutButton onClick={this.handleLogoutClick} />;
                
                <div>
                    <Greeting isLoggedIn={isLoggedIn} />
                    {button}
                </div>
                

                2# 内联 If 与逻辑 && 运算符

                {unreadMessages.length > 0 &&
                    <h2>
                        You have {unreadMessages.length} unread messages.
                    </h2>
                }
                

                更多详情:https://reactjs.org/docs/conditional-rendering.html

                【讨论】:

                  【解决方案8】:

                  基于Array.prototype.slice()方法的另一种方法

                  在父组件中的使用

                  import React from "react";
                  import { ColorList } from "./Color";
                  
                  export default function App() {
                    return <ColorList colors={["red", "green", "blue"]} visibleItemsCount={1} />;
                  }
                  

                  ColorList 组件看起来像这样:

                  import React from "react";
                  
                  // This is just a placeholder component :)
                  function Color({ color }) {
                    return <div style={{ color }}>{color}</div>;
                  }
                  
                  export function ColorList({ colors, visibleItemsCount = 0 }) {
                    const [showMore, setShowMore] = React.useState(false);
                  
                    // Toggle value on click button
                    const onClick = () => setShowMore((value) => !value);
                  
                    // Memoize the color list when props changed
                    const visibleColors = React.useMemo(() => {
                      // If show more items, return the whole array
                      // Otherwise, return a sliced array based on visible items
                      const count = showMore ? colors.count : visibleItemsCount;
                      return colors.slice(0, count);
                    }, [colors, visibleItemsCount, showMore]);
                  
                    console.log(visibleColors);
                    return (
                      <>
                        <h1>Color list</h1>
                        <>
                          {visibleColors.map((color) => (
                            <Color key={color} color={color} />
                          ))}
                        </>
                        <button onClick={onClick}>{showMore ? "Show less" : "Show more"}</button>
                      </>
                    );
                  }
                  

                  注意:我在CodeSandbox上传了代码,你可以查看here

                  【讨论】:

                    【解决方案9】:

                    您可以使用一个名为 react-if 的库。该库可帮助您根据条件进行渲染或不渲染。

                    这是一个例子:

                    const Bar = ({ name, age, drinkingAge }) => (
                        <div>
                            <Header />
                            <If condition={ age >= drinkingAge }>
                                <Then><span className="ok">Have a beer, {name}!</span></Then>
                                <Else><span className="not-ok">Sorry, {name}, you are not old enough.</span></Else>
                            </If>
                            <Footer />
                        </div> )
                    

                    【讨论】:

                      猜你喜欢
                      • 1970-01-01
                      • 1970-01-01
                      • 1970-01-01
                      • 1970-01-01
                      • 1970-01-01
                      • 2018-07-20
                      • 2023-04-10
                      • 1970-01-01
                      相关资源
                      最近更新 更多