Expandbale 文本块中的三个点 React 和 JS

问题描述

我想要的:


折叠(认)块:

text text text
text text text
text text...
<Read more button>

<Read more button> onclick =>

text text text
text text text
text text text
text text text
<Read less button>

<Read less button> onclick => vice versa

我尝试过的:


我已经可以使用展开/折叠功能,但是如何在句子的最后一个单词结束的地方留下三个点? 尝试文本溢出:省略号;仅适用于空白:pre; 但是块只由一行最后三个点组成:

text text...
<Read more button>

我可以随意使用任何 JS 库(更好的 cdn 库)。但是原生 JS/react 解决方案将是最好的!

附注。 如果我可以问关于库/工具推荐的问题,我不是很清楚,所以如果我不被允许,那么请发表评论,我会编辑问题

这是我的代码

我正在使用 material-ui 排版,顺便说一下,有没有使用 material-ui 的组件的解决方案?

const Description = styled(Typography)`
  overflow: hidden;
  height: 128px;
  margin-bottom: 16px;
`;

和组件:

      <Container>
        <Header variant="h4">{props.title}</Header>
        <Description variant="body1">
          <Trans i18nKey={props.description} />
        </Description>
        <Link
          id="readmore"
          onClick={(_e: React.SyntheticEvent) => {
            if (opening) return;
            setopening(true);
            const target = _e.target as HTMLElement;
            if (target.prevIoUsSibling) {
              if (target.innerHTML === "Read more") {
                console.log("opening more description");
                const paragraph = target.prevIoUsSibling as HTMLElement;
                paragraph.style.overflow = "visible";
                paragraph.style.height = "auto";
                target.innerHTML = "Read less";
              } else {
                console.log("closing more description");
                const paragraph = target.prevIoUsSibling as HTMLElement;
                paragraph.style.overflow = "hidden";
                paragraph.style.height = isDesktop ? "72px" : "128px";
                target.innerHTML = "Read more";
              }
              setopening(false);
            }
          }}
        >
          Read more
        </Link>
      </Container>

我也可以考虑不使用任何 js,只使用 React 来重写该代码块,所以我询问任何 React 或 JS 解决方案。

重要提示

文本可能会改变,因为您可以看到它是一个可重复使用的组件,并且块的宽度会根据视口的宽度而变化。这就是为什么我正在寻找一个 JS 解决方案,而不是仅仅用类包装最后一行,比如用三个点来结束。我正在寻找一种算法来确定将块折叠到的最后一行。

非常感谢!

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)