我正在开发一个 React 组件,我需要限制字段中显示的文本,该字段会根据输入组件发生变化。我试图做到这一点,当文本框输入变得比组件的宽度长时,显示可以适合的内容,然后是 ... 。我有一些有用的东西,但它使用 width: 字段来设置文本的宽度,我正在寻找一种响应式的方式来使其适合更多或更少的文本
<span
className='itemTitle'
onMouseLeave={this.handleMouseLeave}
id = 'itemTitle'
style = {{width: '420px', "whiteSpace": "nowrap",
overflow:"hidden !important",
'textOverflow': "ellipsis",
'display': 'inline-block'}}>
{prompt || card.get('promptText')}
</span>
最佳答案
我想出的解决方案如下。
从呈现标题组件的父组件,我添加了一个 ref 并添加了一个调整大小的事件监听器,它将新的 Prop 发送到 ItemTitle 组件。
<div ref={input => {{this.rangeInput = input}}}>
<ItemTitle
prompt={prompt}
{...this.props}
width = {this.state.width}
/>
</div>
updateDimensions = () => {
this.setState({
width: this.rangeInput.offsetWidth
})
}
componentDidMount() {
this.updateDimensions();
window.addEventListener("resize", this.updateDimensions);
}
/**
* Remove event listener
*/
componentWillUnmount() {
window.removeEventListener("resize", this.updateDimensions);
}
Then in ItemTitle.js
<span
className='itemTitle'
onMouseLeave={this.handleMouseLeave}
id = 'itemTitle'
style = {{width: this.state.width - 140, "whiteSpace": "nowrap",
overflow:"hidden !important",
'textOverflow': "ellipsis",
'display': 'inline-block'}}>
{prompt || card.get('promptText')}
</span>
关于css - 随着窗口大小的变化增加文本溢出限制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46373977/