对象可能在引用段落 HTML 元素时'undefined'



我有这个功能组件,我正在尝试获取引用以检查文本是否超过 3 行。这是组件的一部分。

export const Content = ({ content }: contentProps) => {
const myRef: any = useRef(null);
......
const threeLines = (): boolean => {
// @ts-ignore
const offset = myRef.current.offsetHeight;
// @ts-ignore
const lineHeight = parseInt(getComputedStyle(myRef.current).lineHeight);
const lines = Math.floor(offset / lineHeight);
console.log(lines);
return lines < 3;
};
.........
return (
<div className="content">
<p ref={myRef} className={show ? "text" : ""}>
{content}
</p>
<br></br>
{!isThreeLines ? (
<button onClick={showToggle}> See {show ? "more" : "less"} </button>
) : null}
</div>
);

我不想设置 myRef:任何。 怎么了?为什么我收到对象可能是"未定义的"?

编辑:当我删除//@ts-忽略时发生

你想正确输入你的引用,比如:const myRef = useRef<HTMLParagraphElement>(null)

其次,因为你可以在任何地方调用你的函数,所以它不能保证你的ref.current有一个值,所以你必须做一个状态检查或类似的东西;

const threeLines = (): boolean => {
let lines = 0;
if (myRef.current) {
const offset = myRef.current.offsetHeight;
const lineHeight = parseInt(getComputedStyle(myRef.current).lineHeight);
lines = Math.floor(offset / lineHeight);
}
return lines < 3;
};

我知道在您的代码流程中,从您的角度来看,将设置 ref,但您也可以看到为什么会出现类型错误。

最新更新