react實現文字多行溢位顯示省略號的情況下對溢位的顯示Tooltip提示效果
阿新 • • 發佈:2021-01-07
我才發現,我已經整整一年沒有寫過部落格啦,上篇部落格還是一年前的今天~~~
先貼上最後博文講完後要實現的狀態:
我要實現的就是這種很小的功能,第一張圖中的資料是迴圈遍歷出來的,且class中設定了超出隱藏的效果(多行)。
overflow: hidden;
text-overflow: ellipsis;
-webkit-line-clamp: 2; //設定兩行
我剛開始做的時候是判斷了下字元的長度,然後和自己定的一個數字做比較,但是一個非常明顯的問題就是:全部中文、全部英文、大小寫英文寬度又有不同的情況就比較難判斷了。
const getDescriptionLen = description => { let len = 0; for (let i = 0; i < description.length; i++) { const cur = description.charCodeAt(i); if (cur > 127 || cur === 94) { len += 2; } else { len ++; } } return len; }; //render中 { getDescriptionLen(引數) > 28 ? (<Tooltip title={引數}>{引數}</Tooltip>) : 引數 }
我剛才也列舉了這種判斷方式的缺點,可謂是非常多啊!!!
選擇了一種判斷高度的實現方式,在div裡面加個span標籤,div是受style超出隱藏的限制的,但是span標籤是不受限制的,所以就判斷span的寬、高是否大於div,如果大於了div的寬高的時候就顯示Tooltip的資料,否則正常顯示,這樣一來就解決了我上面提出的哪些問題。
html結構:
div的實際高度:
span的實際高度:
//html中 <div className={cx('param-meaning')} ref={parentDom}> { toolTipIsShow ? ( <Tooltip title={description}> <span>{description}</span> </Tooltip> ) : (<span ref={childDom}>{description}</span>) } </div> //js const [parentSize, setParentSize] = useState({}); const [toolTipIsShow, setToolTipIsShow] = useState(false); //儲存一個布林值作為顯示的依賴 //通過ref來獲取html中的DOM // div寬度、高度 const parentDom = useCallback( node => { if (node !== null) { const height = node.getBoundingClientRect().height; //div的真實高度 const width = node.getBoundingClientRect().width; setParentSize({height, width}); } }, [], ); // span寬度、高度 const childDom = useCallback( node => { if (node !== null && parentSize.height) { const height = node.getBoundingClientRect().height; //span的真實高度 const width = node.getBoundingClientRect().width; //判斷一下高度是否大於div的高度 if (height > parentSize.height || width > parentSize.width) { setToolTipIsShow(true); } else { setToolTipIsShow(false); } } }, [parentSize], );
注意的是,這個要單獨寫在一個元件中,因為每個迴圈出來的資料都需要根據當前的狀態進行判斷,每個迴圈出來的內容都要維護一個自己的狀態,所以要單獨寫在一個元件中,這樣才能每個元素維護一個屬於自己的狀態。
本文中獲取 DOM 節點的位置或是大小的基本方式是使用callback ref。官網的連結為:https://react.docschina.org/docs/hooks-faq.html#how-can-i-measure-a-dom-node