对象可能为“ null”。 TS2531定义useScroll挂钩时出错

时间:2019-07-13 16:28:46

标签: javascript reactjs eslint react-hooks

我具有以下组件定义:

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)支票,但没有用。有什么想法吗?

1 个答案:

答案 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]
}