我需要在 React TypeScript 中实现这一点,因此这里是使用 React Hooks 在 TypeScript 中更新的解决方案。如果至少有 4 行文本,此解决方案将返回 true。
我们声明必要的状态变量:
const [overflowActive, setOverflowActive] = useState<boolean>(false);
const [showMore, setShowMore] = useState<boolean>(false);
我们使用useRef声明必要的引用:
const overflowingText = useRef<HTMLSpanElement | null>(null);
我们创建一个检查溢出的函数:
const checkOverflow = (textContainer: HTMLSpanElement | null): boolean => {
if (textContainer)
return (
textContainer.offsetHeight < textContainer.scrollHeight || textContainer.offsetWidth < textContainer.scrollWidth
);
return false;
};
让我们构建一个useEffect,当overflowActive 发生变化时将调用它,并检查我们当前的 ref 对象以确定该对象是否溢出:
useEffect(() => {
if (checkOverflow(overflowingText.current)) {
setOverflowActive(true);
return;
}
setOverflowActive(false);
}, [overflowActive]);
在我们组件的 return 语句中,我们需要将 ref 绑定到适当的元素。我使用Material UI 加上styled-components 所以这个例子中的元素将是StyledTypography:
<StyledTypography ref={overflowingText}>{message}</StyledTypography>
在styled-components中设置组件样式:
const StyledTypography = styled(Typography)({
display: '-webkit-box',
'-webkit-line-clamp': '4',
'-webkit-box-orient': 'vertical',
overflow: 'hidden',
textOverflow: 'ellipsis',
});