ref
никогда не будет null
, так как const
и не является нулевым для начала, поэтому if (ref)
бесполезно.
Тип useRef<T>(x: T | null)
является MutableRefObject<T>
. Здесь T
равно null
, поэтому тип ref.current
равен null
.
Чтобы исправить это, укажите тип, который будет после его установки:
const ref = useRef(null as null | HTMLDivElement);
// Or manually specify the type parameter
const ref = useRef<HTMLDivElement>(null)
useLayoutEffect(() => {
if (ref.current && ref.current.clientHeight) {
const height = ref.current.clientHeight;
setHeight(height);
}
});