You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React收件人面板文本自适应截断实现求助

React 收件人面板实现优化

需求说明

  • 开发收件人展示面板,用于呈现发件人的所有收件人邮箱地址
  • 容器空间充足时,以逗号分隔完整显示所有收件人地址
  • 空间不足时,自动截断文本以显示尽可能多的收件人,末尾添加+N样式徽章(N代表未显示的收件人数量)

当前实现代码

React 逻辑代码

useEffect(() => {
    const handleResize = () => {
      if (containerRef.current) {
        const containerWidth = containerRef.current.offsetWidth;
        const screenWidth = window.innerWidth;
        setShowAll(containerWidth >= screenWidth);
      }
    };

    handleResize();

    window.addEventListener('resize', handleResize);
    return () => {
      window.removeEventListener('resize', handleResize);
    };
  }, [recipients]);

  const displayRecipients = showAll ? recipients : recipients.slice(0, calculateVisibleRecipients(recipients));

  return (
    <div
      ref={containerRef}
      className={`recipients-display ${showAll ? 'show-all' : ''}`}
      style={{ whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', maxWidth: '100vw' }}
    >
      {displayRecipients.join(', ')}
      {!showAll && recipients.length > displayRecipients.length && (
        <span className="badge">+{recipients.length - displayRecipients.length}</span>
      )}
    </div>
  );
};

CSS 样式代码

.content {
  display: flex; /* 使内容成为flex容器 */
  justify-content: space-between; /* 文本与徽章之间的间距 */
  align-items: center; /* 垂直居中对齐 */
}

.badge {
  background-color: #666666; /* 自定义徽章背景色 */
  color:  #f0f0f0; /* 自定义徽章文字颜色 */
  padding: 2px 5px;
  margin-left: 10px; /* 与行尾的间距 */
  border-radius: "3px";
}

.overflow-indicator {
  margin-left: 5px;
  color: #777; /* 自定义溢出指示器颜色 */
}

本人不擅长CSS,希望优化当前实现以达成预期效果。

内容的提问来源于stack exchange,提问作者thegreenmilecasablanca

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 08:50:56