【问题标题】:Returning null when condition is met does not work满足条件时返回 null 不起作用
【发布时间】:2023-02-09 02:44:34
【问题描述】:

我有一个问题,我的数据返回空 div,即使它不应该显示任何东西 - 导致我的设计被破坏。

const data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];

  const itemsToDisplay = data.slice(0, 5);
  const remainingItemsCount = data.length - itemsToDisplay.length;

  <PackedGrid boxAspectRatio={aspectRatio} className="fullscreen">
    {itemsToDisplay.map((i) => (
      <GridItemPlaceholder>{i}</GridItemPlaceholder>
    ))}
    {remainingItemsCount > 20 ? (
      <GridItemPlaceholder>+{remainingItemsCount}</GridItemPlaceholder>
    ) : null}
  </PackedGrid>`

上面的案例应该返回网格中间的项目 5,但它位于左侧,这是因为 remainingItemsCount 仍在其右侧返回一个空的 div - 您可以检查以查看它。

我写了一个应该保持为空的条件,但它不起作用。我相信问题出在我使用的包中,但必须有一些解决方案吗?

这是代码示例

https://codesandbox.io/s/grid-16-9-ratio-forked-5qt1rx?file=/src/App.js

【问题讨论】:

    标签: reactjs next.js grid tailwind-css aspect-ratio


    【解决方案1】:

    您可以在项目 5 的右侧看到空的 div。

    解决它的一种方法是进行额外检查,如果剩余的 ItemsCount 为 0,则返回 null 而不是 div。

    <PackedGrid boxAspectRatio={aspectRatio} className="fullscreen">
        {itemsToDisplay.map((i) => (
          <GridItemPlaceholder>{i}</GridItemPlaceholder>
        ))}
        {remainingItemsCount > 0 ? (
          <GridItemPlaceholder>+{remainingItemsCount}</GridItemPlaceholder>
        ) : null}
      </PackedGrid>
    

    【讨论】:

      最近更新 更多