css - 随着窗口大小的变化增加文本溢出限制

标签 css reactjs

我正在开发一个 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/

相关文章:

javascript - 我如何使 PHP/HTML 图像在单击时显示原始大小?

javascript - Reactjs dropzone未将所有拖放的文件上传到reactjs中的firebase firestore数据库

javascript - 从 API 在 React 中显示 Json 对象

reactjs - Jest 测试模拟——在另一个函数中模拟获取

reactjs - 输入范围 slider 作为 react Hook 不滑动

javascript - 在运行时使用 javascript 加载 div 背景图像(通过/使用?CSS)

css - 单击某物时的虚线边框样式

javascript - 具有动态 div 的 CSS 垂直居中

CSS 边框在页面收缩时不可见

node.js - Webpack、开发中间件和静态文件