【问题标题】:How to truncate a overflowed text in a react element with middle ellipsis?如何用中间省略号截断反应元素中溢出的文本?
【发布时间】:2018-07-26 18:54:31
【问题描述】:

我是新来的反应。所以非常感谢任何帮助。我有一个反应表,其中一列包含每一行的名称。我有像“entry”、“entry (1)”、...“entry (n)”这样的名字 我希望能够在名称很长时处理文本溢出,但我想保留名称的索引,因此不能使用 css (text-overflow:"ellipses"

有没有办法让我“ent...(n)”?

【问题讨论】:

标签: javascript reactjs


【解决方案1】:

您可以通过结合使用 flexbox 和 position: absolute 来实现。绝对位置可防止 div 影响表格列的宽度,同时填充 td 的全宽。 flexbox 限制了文本区域的宽度,这使得省略号的外观成为可能:

const Entry = ({ children, index }) => (
  <div className="entry">
    <div className="entry__inner">
      <span className="entry__text">{children}</span>
      <span className="entry__index">({index})</span>
    </div>
  </div>
);

const Demo = ({ entries }) => (
  <table>
    <thead>
      <th>Name</th>
    </thead>
    <tbody>
      {entries.map((text, index) => (
        <tr key={index}>
          <td>
            <Entry index={index}>{text}</Entry>
          </td>
        </tr>
      ))}
    </tbody>
  </table>
);

const entries = ['entry', 'long entry', 'long long entry'];

ReactDOM.render(
  <Demo entries={entries} />,
  demo
);
td {
  width: 5.5em;
}

.entry {
  position: relative;
  height: 1em;
}

.entry__inner {
  position: absolute;
  display: flex;
  left: 0;
  right: 0;
}

.entry__text {
  flex: 1;
  margin-right: 0.5em;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.entry__index {
  text-align: right();
}
<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="demo"></div>

【讨论】:

    猜你喜欢
    • 2016-10-18
    • 1970-01-01
    • 2022-01-23
    • 2011-05-17
    • 1970-01-01
    • 2016-11-15
    • 2011-09-17
    • 1970-01-01
    相关资源
    最近更新 更多