【问题标题】:Complex conditional rendering复杂的条件渲染
【发布时间】:2019-03-09 14:09:01
【问题描述】:

我有一个组件的 2 个版本,一个移动响应版本和一个桌面。现在,在渲染任一组件之前需要满足几个条件,如下所示:

{condition &&
    !otherCondition &&
    (size === "small" || size === "extra-small") && (
        <MobileComponent />
    )}

{condition &&
    !otherCondition &&
    (size !== "small" || size !== "extra-small") && (
        <DesktopComponent />
    )}

但是,这似乎不起作用,并且组件的移动版和桌面版都已呈现。它只会在我想说的(size === "small" || size === "extra-small") 部分出现问题:

如果大小为small 或大小为extra small,则显示移动组件。

然后反过来……

如果大小不是small 或大小不是extra small,则显示桌面组件。

请注意,每当我调整屏幕大小时,small 的值都会发生变化。所以价值在于我做这个条件的方式有问题。

【问题讨论】:

  • 认为桌面条件应该是如果 size 不是 small AND 它不是 extra-small,而不是 OR。 OR 使该条件评估为真,因为如果它是 smallsize !== "extra-small" 将为真,反之亦然。

标签: javascript reactjs components


【解决方案1】:

(size === "small" || size === "extra-small") 可以被否定

!(size === "small" || size === "extra-small") 

(size !== "small" && size !== "extra-small") 

请注意,=== 和逻辑 OR 都已更改。

由于相同的条件被使用了两次,一个更干更易读的写法是:

const isMobile = condition && !otherCondition && (size === "small" || size === "extra-small");
...
{isMobile && <MobileComponent />}
...
{!isMobile && <DesktopComponent />}

如果组件是连续的,那么应该使用三元:

{isMobile ? <MobileComponent /> : <DesktopComponent />}

【讨论】:

    【解决方案2】:

    我相信你打算这样做:

    {condition &&
        !otherCondition &&
        (size !== "small" && size !== "extra-small") && (
            <DesktopComponent />
        )}
    

    问题是在 size="small" 的情况下,然后您的两个条件都被评估为 true。(在 &lt;MobileComponent&gt; 中很明显,在 &lt;DesktopComponent&gt; 中因为“small”实际上与“extra-small”不同"

    【讨论】:

      【解决方案3】:

      试试下面的三元运算符

         {condition && !otherCondition && (size === "small" || size === "extra-small") ? <MobileComponent /> : <DesktopComponent />}
      

      【讨论】:

        猜你喜欢
        • 2020-02-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-25
        • 2012-05-10
        • 2019-12-20
        • 2020-07-30
        • 2016-08-25
        相关资源
        最近更新 更多