Я должен поместить текст в контейнер 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" />