多行文本以适应 React JS 中的父容器

IT技术 javascript reactjs
2021-05-11 04:29:37

我正在使用 flexbox 布局,并试图让特定 div 中的文本调整大小以适合该 div。

例如,如果我有如下代码:

<div style={{display: "flex"}}>
   <div style={{flex: 1}}>
      A really, really, really, really long phrase here that will fit this div, and may wrap onto multiple lines if necessary. In this case it should fill half of the available space as the other div will cover the other half of the space.
   </div>
   <div style={{flex: 1}}>
      Some other text
   </div>
</div>

实际上,文本将从数据库中提取,因此长度是动态的。

如何让第一个 div 中的文本自动调整以适合整个 div?

澄清: div 应该保持固定大小,只有文本应该缩小以适应 div 而不是溢出 div。

更新

我还发布了一个更具体的问题,关于一个名为react-textfit的特定module没有按照我期望的方式工作。

4个回答

这是一些应该按照您的要求执行的代码。

let size_div = document.querySelector("#font_size");
let div = document.querySelector("#fixed");

while (div.scrollHeight > div.clientHeight) {
  let style = window.getComputedStyle(div, null).getPropertyValue('font-size');
  let fontSize = parseFloat(style);

  if (fontSize <= 1) {
    break;
  }

  div.style.fontSize = "" + (fontSize - 1) + "px";
  size_div.innerHTML = "&nbsp;" + div.style.fontSize;
}

在此处输入图片说明 在此处输入图片说明

你可以在这里尝试:https : //codepen.io/lowtex/pen/xNawEO

您可以简单地将大小硬编码为 50%

<div style="display:flex">
  <div style="width:50%;background:lightgrey;">
    A really, really, really, really long phrase here that will fit this div, and may wrap onto multiple lines if necessary. In this case it should fill half of the available space as the other div will cover the other half of the space.
  </div>
  <div style="width:50%;background:lightblue;">
    Some other text
  </div>
</div>

在此处输入图片说明

我不是 reactJs 用户,但我使用过 CSS flex

您可以将容器的高度设置为自动,以便它随着我们获取内容而变化。此外,您应该max-height在 css 中设置 min-height 和属性,以便如果内容小于给定的长度,它就会出现min-height,如果内容太大,它不会超过给定的容器高度。

为了禁止内容开箱即用,您可以使用overflow:hidden. 这将防止内容开箱即用。

希望这对您要如何继续提供一些帮助。

<div style={{ display: "flex" }}>
<div
    style={{
    flex: 1,
    backgroundColor: "lightGrey",
    wordBreak: "break-word"
    }}
>
    A really, really, really, really long phrase here that will fit this
    div, and may wrap onto multiple lines if necessary. In this case it
    should fill half of the available space as the other div will cover
    the other half of the space.
</div>
<div style={{ flex: 1, backgroundColor: "lightBlue" }}>
    Some other text
</div>
</div>