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

标签 javascript reactjs

我正在使用 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。

更新

我还发布了一个 more specific question关于名为 react-textfit 的特定模块未按我预期的方式工作。

最佳答案

这里有一些代码可以满足您的要求。

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;
}

enter image description here enter image description here

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

关于javascript - 多行文本以适应 React JS 中的父容器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56301566/

相关文章:

javascript - Chrome 中的 HTML5 网络摄像头捕获缩放问题

javascript - 输入表单后 react 条件显示/隐藏不起作用

javascript - p5向量减法 'sub'返回错误

javascript - 过滤列表中的数据(删除按钮)不起作用?

javascript - 如何在 react 中一项一项地渲染列表中的项目?

javascript - Java脚本中的游戏。我应该使用 Canvas 吗?

javascript - 从 Controller 访问模型。 Angular .js

javascript - webpack 没有正确添加 [contenthash] 到我的 .js 文件

javascript - AngularJS 1.x 依赖下拉菜单 : third level not getting reset when changing first level

html - 如何在React中运行 "index.html"