【问题标题】:Hide entire block of text whenever it no longer fits不再适合时隐藏整个文本块
【发布时间】:2022-02-11 05:12:33
【问题描述】:

我的文本似乎默认隐藏不适合 div 的特定部分。一旦不再适合,我希望整个街区消失。

有什么办法吗?

这是我目前拥有的示例应用程序:

const App = () => {

  return (
    <div className='container'>
      <p className='text'> If you don't fit you need to be hidden. If you don't fit you need to be hidden.If you don't fit you need to be hidden.If you don't fit you need to be hidden.If you don't fit you need to be hidden.If you don't fit you need to be hidden.If you don't fit you need to be hidden.If you don't fit you need to be hidden.If you don't fit you need to be hidden.If you don't fit you need to be hidden.If you don't fit you need to be hidden.If you don't fit you need to be hidden.If you don't fit you need to be hidden.If you don't fit you need to be hidden.If you don't fit you need to be hidden.If you don't fit you need to be hidden.</p>
    </div>
  )
}


ReactDOM.render(
    <App />,
    document.getElementById('app')
);
.container {
  border: 1px solid red;
  height: 150px;
  width: 150px;
  overflow: hidden;

}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.0/umd/react-dom.production.min.js"></script>
<div id="app"></div>

【问题讨论】:

  • 我不认为使用纯 CSS 可以做到这一点。但是您可以将 ref 附加到元素并在溢出时通过反应有条件地显示它。检查元素是否溢出,可以使用element.scrollWidth &gt; element.offsetWidth
  • 我的回答对你有用吗?

标签: javascript css reactjs sass


【解决方案1】:

TL;DR:工作示例here


我认为没有 css 方法可以做到这一点,但由于您使用的是 React,您可以利用 refs 并计算元素大小。

1。获取对元素的引用

请注意,您不能使用标准的 useRef 挂钩(据我所知),因为对这些挂钩的更改不会触发重新渲染,因此 React 不会知道您的容器何时溢出。 相反,您可以使用 callback ref 并将其存储在状态中。

const [textRef, setTextRef] = useState(null);

...

<div ref={(newRef) => setTextRef(newRef)} className="container">
  ...
</div>

2。检查是否溢出

现在您有了对该元素的引用,您可以通过比较 scrollHeightoffsetHeight 属性来计算它是否溢出。

const overflows = textRef.scrollHeight > textRef.offsetHeight;

3。在状态中存储信息

您必须在元素更改时动态执行此操作,因此请将其放在 useEffect 挂钩中,并以 textRef 作为依赖项。然后将“溢出”属性存储在状态中以供以后使用。

const [overflows, setOverflows] = useState(false);

useEffect(() => {
  if (textRef) {
    const overflows = textRef.scrollHeight > textRef.offsetHeight;
    setOverflows(overflows);
  }
}, [textRef]);

4。有条件地渲染

现在您知道元素是否溢出并且状态中包含该信息,您可以简单地有条件地渲染元素。

<div ref={(newRef) => setTextRef(newRef)} className="container">
  {!overflows && <p className="text">If you don't fit you need to be hidden...</p>}
</div>

查看working example,您可以看到其中一个元素显示是因为它的文本较少且适合,而另一个元素因为溢出而被隐藏。

【讨论】:

  • 附言。如果你这样做(newRef) =&gt; textRef.current = newRef,你可以用 refs 达到同样的效果
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-04-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-10
相关资源
最近更新 更多