Многострочный текст для соответствия родительскому контейнеру в React JS - программирование

Многострочный текст для соответствия родительскому контейнеру в React JS

Я использую макет 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.

Обновить

Я также опубликовал более конкретный вопрос о конкретном модуле, который называется response-textfit, и работает не так, как я ожидал.

4b9b3361

Ответ 1

Вы можете просто жестко кодировать размер до 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>

enter image description here

Ответ 2

Вот код, который должен делать то, что вы просите.

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

Ответ 3

Это не столько проблема ReactJS, сколько CSS/Flexbox.

Вы попросили заполнить весь блок, который вообще не потребовал бы flexbox, поэтому я предполагаю, что вы намеревались заполнить большую часть пространства, пока 2-й блок сокращается.

Вам просто нужно снять flex: 1 со второго 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>
      Some other text
   </div>
</div>

Ответ 4

Я не пользовательactJs, но я работал с CSS flex

Вы можете установить высоту контейнера автоматически, чтобы она изменялась по мере получения содержимого. Кроме того, вы должны установить свойства min-height и max-height в css, чтобы, если содержимое меньше заданной длины, оно отображалось на min-height а если содержимое было слишком большим, оно не превышало заданную высоту контейнера.

Чтобы запретить контенту выходить из коробки, вы можете использовать overflow:hidden. это не даст контенту выйти из коробки.

Надеюсь, что это поможет вам в дальнейшей работе.

Ответ 5

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

Ответ 6

То, что вы попробовали, правильно, посмотрите на этот пример:

function App() {

  const addText = () => {
    document.querySelector('.child').innerHTML += " 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.";
  }

  const reset = () => {
    document.querySelector('.child').innerHTML = "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.";
  }

  return (
    <React.Fragment>
      <button onClick={() => addText()}>Add text</button> 
      <button onClick={() => reset()}>Reset</button><br /><br />
      
      <div style={{display: "flex"}}>
         <div className="child" 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>
    </React.Fragment>
  )
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

<div id="root"></div>