Подгонка текста внутри контейнера за счет уменьшения размера шрифта и сокращения текста - PullRequest
0 голосов
/ 04 сентября 2018

Я должен поместить текст в контейнер div, который является квадратным. Если текст слишком велик, чтобы поместиться в контейнере, я должен уменьшить размер шрифта с 32 до 18 пикселей. И даже если это не подходит, я должен обрезать текст с "...". Это выглядит достаточно просто. Я использую простой JavaScript / React.

Есть несколько подходов, которые я пробую.

<div className="container" ref={c => { this.comp = c; }}>
  {text}
</div>

Если clientHeight

if (this.comp.clientWidth < this.comp.scrollHeight) {
  this.setState({ overflow: true });
}

Я устанавливаю стиль для контейнера на основе изменений состояния.

style={this.state.overflow ? { fontSize: 18 } : undefined}

Мне нравится сокращать текст, если он по-прежнему переполняется. Не уверен, как обрезать текст.

Фрагмент кода:

class App extends React.Component {
  constructor() {
    super();
    this.state = {};
  }

  componentDidMount() {
    if (this.comp.clientHeight < this.comp.scrollHeight) {
      console.log('reducing font size from 32px to 18px');
      this.setState({ overflow: true });
    }
  }
  
  render() {
    const { overflow } = this.state;
    return (
      <div className="container" 
           ref={c => { this.comp = c; }} 
           style={overflow ? { fontSize: 18 } : undefined}
      >
        This is a long text which wont fit within the container. Inspite of reducing the font size, it wont fit. And I want to truncate with ellipsis. It is not possible with text-overflow as it is multi-line text. How do I figure how many characters to truncate it to?
      </div>
    );
  }
}


ReactDOM.render(<App />, document.getElementById('root'));
.container {
  display: inline-block;
  width: 200px;
  height: 200px;
  background-color: #fafafa;
  padding: 10px;
  font-size: 32px;
  overflow: hidden;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root" />

1 Ответ

0 голосов
/ 05 сентября 2018

Это может быть сделано путем обновления текста компонента до его соответствия. И вот, наконец, установка состояния. Фрагмент кода показан ниже.

class App extends React.Component {
  constructor() {
    super();
    this.state = {};
  }

  componentDidMount() {
    let overflow;
    if (this.comp.clientHeight < this.comp.scrollHeight) {
      overflow = true;
      this.comp.style.fontSize = '18px';
    }
    let truncatedText;
    while (this.comp.clientHeight < this.comp.scrollHeight) {
      const words = this.comp.innerText.split(' ');
      words.pop();
      truncatedText = words.join(' ') + '...';
      this.comp.innerText = truncatedText;
    }
    this.setState({
      overflow,
      truncatedText
    });
  }

  render() {
    const {
      overflow,
      truncatedText
    } = this.state;
    const text = 'This is a long text which wont fit within the container.Inspite of reducing the font size, it wont fit.And I want to truncate with ellipsis.It is not possible with textoverflow as it is multiline text.How do I figure how many characters to truncate it to.';
    
    return ( <div className = "container"
      ref = {
        c => {
          this.comp = c;
        }
      }
      style = {
        overflow ? {
          fontSize: 18
        } : undefined
      }>
      {truncatedText || text} 
      </div>
    );
  }
}


ReactDOM.render( <App /> , document.getElementById('root'));
.container {
  display: inline-block;
  width: 200px;
  height: 200px;
  background-color: #fafafa;
  padding: 10px;
  font-size: 32px;
  overflow: hidden;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root" />

Продолжайте сокращать текст до тех пор, пока он не уместится, и, наконец, обновите состояние.

    let truncatedText;
    while (this.comp.clientHeight < this.comp.scrollHeight) {
      const words = this.comp.innerText.split(' ');
      words.pop();
      truncatedText = words.join(' ') + '...';
      this.comp.innerText = truncatedText;
    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...