Reactjs 对象可能是';未定义';参考段落HTML元素
我有这个功能组件,我正在尝试获取参考来检查文本是否包含超过3行。这是组件的一部分Reactjs 对象可能是';未定义';参考段落HTML元素,reactjs,typescript,reference,react-hooks,Reactjs,Typescript,Reference,React Hooks,我有这个功能组件,我正在尝试获取参考来检查文本是否包含超过3行。这是组件的一部分 export const Content = ({ content }: contentProps) => { const myRef: any = useRef(null); ...... const threeLines = (): boolean => { // @ts-ignore const offset = myRef.current.offsetHeight
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>
);
export const Content=({Content}:contentProps)=>{
const myRef:any=useRef(null);
......
常量三行=():布尔=>{
//@ts忽略
常数偏移=myRef.current.offsetHeight;
//@ts忽略
const lineHeight=parseInt(getComputedStyle(myRef.current).lineHeight);
常数线=数学楼层(偏移/线高);
控制台日志(行);
回流线<3;
};
.........
返回(
{content}
{!是三线吗(
参见{显示?“更多”:“更少”}
):null}
);
我不想设置myRef:any。
问题是什么?为什么我接收的对象可能是“未定义的”
编辑:当我删除//@ts ignore时会发生此错误。您希望正确键入ref,如:
const myRef=useRef(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;
};
constThreeLines=():布尔=>{
设直线=0;
如果(myRef.current){
常数偏移=myRef.current.offsetHeight;
const lineHeight=parseInt(getComputedStyle(myRef.current).lineHeight);
线条=数学楼层(偏移/线条高度);
}
回流线<3;
};
我知道在您的代码流中,从您的角度来看,ref将被设置,但您也可以看到为什么会出现类型错误。从哪里得到该错误?您可以看到//@ts ignore