使用一个三元运算符渲染多个组件

时间:2020-02-20 03:06:48

标签: javascript reactjs

如果为currentProfiles.length > 0,我想映射到一个名为profile的数组并为每个配置文件渲染一个配置文件组件,在这些配置文件下渲染一个分页组件。我用一个三元运算符尝试过此操作,但这导致仅呈现分页组件。

    {currentProfiles.length > 0 ? (
      (currentProfiles.map(profile => (
        <ProfileItem key={profile._id} profile={profile} />
      )),
      (
        <Pagination
          profilesPerPage={profilesPerPage}
          totalProfiles={profiles.length}
        />
      ))
    ) : (
      <Spinner />
    )}

如果我使用两个单独的三元运算符,则可以按预期获得配置文件和分页列表,但是我可以使用一个条件运算符来完成这两项工作吗?

2 个答案:

答案 0 :(得分:1)

您的代码只需要进行一些重组。如果将映射的配置文件和分页组件包装在父片段或其他元素中,则很容易。同样请注意,下面的第一个示例仍应要求保留三进制。

  return (
    <div className="App">
      {currentProfiles.length ? (
        <>
          {currentProfiles.map(p => (
            <Profile {...p} />
          ))}
          <Pagination profilesPerPage={2} totalProfiles={totalProfiles} />
        </>
      ) : (
        <p>Loading...</p>
      )}
    </div>
  );

但是,除了将它们包装在未呈现的Fragment或它的简写形式中之外,您还有其他选择。您也可以使用实际元素,例如div。甚至完全忽略父级,并将您的逻辑放在数组中,如:

<div className="App">
  {currentProfiles.length ? [
    currentProfiles.map(p => (
      <Profile {...p} />
    )),
    <Pagination profilesPerPage={2} totalProfiles={totalProfiles} />
  ] : <p>Loading...</p>}
</div>

请始终记住,除非您使用第二种方法,否则您需要确保兄弟姐妹共享一个共同的父母。

Working example

答案 1 :(得分:0)

您可以使用数组或片段https://reactjs.org/docs/fragments.html

{currentProfiles.length > 0 ? (
     <>
      currentProfiles.map(profile => (
        <ProfileItem key={profile._id} profile={profile} />
      )

        <Pagination
          profilesPerPage={profilesPerPage}
          totalProfiles={profiles.length}
        />
      </>
    ) : (
      <Spinner />
    )}