【问题标题】:Object is possibly 'null'. TS2531 Error when defining useScroll hook对象可能为“空”。 TS2531 定义 useScroll 挂钩时出错
【发布时间】:2019-11-23 01:06:11
【问题描述】:

我有以下组件定义:

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) 检查,但没有工作。有什么想法吗?

【问题讨论】:

  • ref.current 为空

标签: javascript reactjs eslint react-hooks


【解决方案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]
}

【讨论】:

猜你喜欢
  • 2021-02-14
  • 1970-01-01
  • 2021-07-11
  • 2021-08-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-22
相关资源
最近更新 更多