我试图找出一个div是否溢出了文本,如果溢出了就显示show more
链接。我找到了this stackoverflow answer to check if a div is overflowing。根据这个答案,我需要实现一个函数,它可以访问有问题的元素的样式,并检查它是否溢出。我如何访问元素的样式。我尝试了两种方法
1.使用ref
import React from "react";
import "./styles.css";
export default function App(props) {
const [showMore, setShowMore] = React.useState(false);
const onClick = () => {
setShowMore(!showMore);
};
const checkOverflow = () => {
const el = ref.current;
const curOverflow = el.style.overflow;
if ( !curOverflow || curOverflow === "visible" )
el.style.overflow = "hidden";
const isOverflowing = el.clientWidth < el.scrollWidth
|| el.clientHeight < el.scrollHeight;
el.style.overflow = curOverflow;
return isOverflowing;
};
const ref = React.createRef();
return (
<>
<div ref={ref} className={showMore ? "container-nowrap" : "container"}>
{props.text}
</div>
{(checkOverflow()) && <span className="link" onClick={onClick}>
{showMore ? "show less" : "show more"}
</span>}
</>
)
}
2.使用正向参考
- 子组件 *
export const App = React.forwardRef((props, ref) => {
const [showMore, setShowMore] = React.useState(false);
const onClick = () => {
setShowMore(!showMore);
};
const checkOverflow = () => {
const el = ref.current;
const curOverflow = el.style.overflow;
if (!curOverflow || curOverflow === "visible") el.style.overflow = "hidden";
const isOverflowing =
el.clientWidth < el.scrollWidth || el.clientHeight < el.scrollHeight;
el.style.overflow = curOverflow;
return isOverflowing;
};
return (
<>
<div ref={ref} className={showMore ? "container-nowrap" : "container"}>
{props.text}
</div>
{checkOverflow() && (
<span className="link" onClick={onClick}>
{showMore ? "show less" : "show more"}
</span>
)}
</>
);
});
- 父组件 *
import React from "react";
import ReactDOM from "react-dom";
import { App } from "./App";
const rootElement = document.getElementById("root");
const ref = React.createRef();
ReactDOM.render(
<React.StrictMode>
<App
ref={ref}
text="Start editing to see some magic happen! Click show more to expand and show less to collapse the text"
/>
</React.StrictMode>,
rootElement
);
但是我在两种方法中都得到了下面的错误-Cannot read property 'style' of null
。我做错了什么?我怎样才能达到我想要的?
3条答案
按热度按时间wz1wpwve1#
正如Jamie狄克逊在评论中建议的那样,我使用了
useLayoutEffect
hook来设置showLink
为true。组件
中央支助组
ny6fqffe2#
我们可以创建一个自定义钩子来知道是否有溢出。
然后签入您的组件
感谢Robin Wieruch的精彩文章https://www.robinwieruch.de/react-custom-hook-check-if-overflow/
jmo0nnb33#
使用TS和钩的解决方案
创建自定义钩子:
用你的钩子:
根据需要导入文件并根据需要更新代码。