我具有以下组件定义:
import { useRef } from 'react';
export default function useScroll() {
const ref = useRef(null)
const executeScroll = () => {
if (ref != null)
window.scrollTo(0, ref.current.offsetTop)
}
const htmlElementAttributes = { ref }
return [executeScroll, htmlElementAttributes]
}
第window.scrollTo(0, ref.current.offsetTop)
行引发错误。我已包括if (ref != null)
支票,但没有用。有什么想法吗?
答案 0 :(得分:1)
尝试ref.current !== null
,因为:
const ref = useRef(null); // ref is object { current: null }
ref !== null; // always true
import { useRef } from 'react';
export default function useScroll() {
const ref = useRef(null)
const executeScroll = () => {
if (ref.current !== null)
window.scrollTo(0, ref.current.offsetTop)
}
const htmlElementAttributes = { ref }
return [executeScroll, htmlElementAttributes]
}