【问题标题】:Solve the typescript - "No matches overload call" with ref解决打字稿 - \"No matches overload call\" with ref
【发布时间】:2023-01-27 00:03:18
【问题描述】:

我要解决打字稿记者。 这是代码和我得到的错误。

const navRef = useRef<null | HTMLElement>(null);

const setFocusables = () => {
  let navCurrent = navRef.current || null;
  menuFocusables = [
    buttonRef.current,
    ...Array.from(navCurrent?.querySelectorAll('a')),
  ];
  firstFocusableEl = menuFocusables[0];
  lastFocusableEl = menuFocusables[menuFocusables.length - 1];
};

这是我现在得到的错误。

让 navCurrent: HTMLElement | null 没有重载匹配此调用。
重载 1 of 4, '(iterable: Iterable | ArrayLike): HTMLAnchorElement[]', 给出了 以下错误。 “NodeListOf”类型的参数 | undefined' 不可分配给类型的参数 '可迭代 | ArrayLike'。
类型“未定义”不可分配给类型 '可迭代 | ArrayLike'。
重载 2 of 4, '(arrayLike: ArrayLike): HTMLAnchorElement[]',出现以下错误。类型参数 '节点列表| undefined' 不可分配给 “ArrayLike”类型的参数。类型 “未定义”不可分配给类型 'ArrayLike'.ts(2769)

请给我解决方案。 先感谢您。

你好。

希望能解决以上问题。

谢谢

【问题讨论】:

    标签: reactjs typescript react-proptypes use-ref


    【解决方案1】:

    navCurrent 为空时,您需要处理,因此它应该是这样的:

    const navRef = useRef<null | HTMLElement>(null);
    
    const setFocusables = () => {
      let navCurrent = navRef.current || null;
      menuFocusables = [
        buttonRef.current,
        // updated this
        ...Array.from(navCurrent?.querySelectorAll('a') ?? []),
      ];
      firstFocusableEl = menuFocusables[0];
      lastFocusableEl = menuFocusables[menuFocusables.length - 1];
    };
    

    【讨论】:

    • 谢谢您的回答。它对我有用。
    • 乐于帮助!能否请您标记为已回答,以便人们知道它已解决:)
    猜你喜欢
    • 2018-07-05
    • 2021-06-19
    • 2021-08-10
    • 2019-06-02
    • 1970-01-01
    • 2022-11-18
    • 1970-01-01
    • 2021-08-21
    • 2015-03-01
    相关资源
    最近更新 更多