【问题标题】:React js hide rows when too many elements in a list当列表中的元素太多时,React js隐藏行
【发布时间】:2022-01-16 21:54:50
【问题描述】:

我正在水平显示带有头像的用户列表,当他们很多或显示很小时,会出现一个新行。现在,如果出现第三行,我想隐藏它并显示显示更多按钮,并且应该只有 2 行可见。

有人可以帮我吗?我知道如何仅使用文本来实现它,但这里的用户组件包括头像、角色和用户名,因为我不能使用 line_height 并计算行数。

<ul>{data.map(item => <li style={{display: "inline-block"}}><DisplayUser user={item}/></li>)}</ul>

用户组件

      <UserData>
        {user.avatarUrl && (
          <Avatar
            sx={{ marginRight: "10px", width: 42, height: 42 }}
            src={user.avatarUrl}
          />
        )}
        <Box
          sx={{
            display: "flex",
            flexDirection: "column",
            alignItems: "flex-start",
          }}
        >
          <Typography variant="body1" sx={{ lineHeight: "inherit" }} noWrap>
            {user.userName}
          </Typography>
          <Typography
            variant="caption"
            sx={{ color: "var(--text-secondary)" }}
            noWrap
          >
            {user.role}
          </Typography>
        </Box>
      </UserData>

【问题讨论】:

    标签: javascript css reactjs


    【解决方案1】:

    您可以使用state.num 而不是line-height 来保存要渲染的项目数,并在单击按钮时增加它。

    增加函数(函数组件)

    const [num, setNum] = useState(0)
    const increaseNum = () => {
      setNum(num + 2)
    }
    

    渲染

    data.map((item, index) => {
      if (index > num) { return false } // end loop
      return (
        <UserData>
          ...
        </UserData>
      )
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-04-08
      • 1970-01-01
      • 2019-05-09
      • 2020-12-28
      • 1970-01-01
      • 1970-01-01
      • 2019-03-28
      相关资源
      最近更新 更多