【问题标题】:typescript - Question about React typescript useReftypescript - 关于 React typescript useRef 的问题
【发布时间】:2021-06-18 18:12:33
【问题描述】:

目标是制作一个影响 DOM 的可重用钩子。

示例代码:

import { useEffect, useRef } from 'react';

function useFocus() {
  const domRef = useRef<HTMLElement | null>(null);

  useEffect(() => {
    domRef.current?.focus()
  }, []);

  return {
    domRef
  };
}

const App = () => {
  const { domRef } = useFocus();

  return (
    <div>
      <input type='text' ref={domRef} />
    </div>
  );
};

export default App;

发生错误:

TypeScript error in /Users/yoki/Code/Demos/use-ref-demo/src/App.tsx(20,26):
Type 'MutableRefObject<HTMLElement | null>' is not assignable to type 'LegacyRef<HTMLInputElement> | undefined'.
  Type 'MutableRefObject<HTMLElement | null>' is not assignable to type 'RefObject<HTMLInputElement>'.
    Types of property 'current' are incompatible.
      Type 'HTMLElement | null' is not assignable to type 'HTMLInputElement | null'.
        Type 'HTMLElement' is missing the following properties from type 'HTMLInputElement': accept, align, alt, autocomplete, and 49 more.  TS2322

    18 |   return (
    19 |     <div>
  > 20 |       <input type='text' ref={domRef} />
       |                          ^
    21 |     </div>
    22 |   );
    23 | }; 

问题:如何为 useRef<...>() 提供正确的类型?

正确的想法是给出从 HTMLElememnt 扩展的任何类型的类型,而不是任何或断言,请帮助。

dom不限于input,可以是div或者input或者span等,所以HTMLInputElement类型不适合这种情况。

【问题讨论】:

  • 不是对象类型吗?

标签: javascript reactjs typescript react-hooks frontend


【解决方案1】:

仔细查看错误消息:Type 'HTMLElement | null' is not assignable to type 'HTMLInputElement | null'.。根据消息,正确的类型是HTMLInputElement | null。另外,稍微改变一下useFocus 是有意义的:

useEffect(() => {
    domRef.current?.focus()
  }, [domRef]);

【讨论】:

  • 谢谢,但我们不应该知道 dom 的类型,它可以是任何 dom。
  • 在这种情况下,把 React.useRef(null)
  • 我还要求不要使用 any : ( 因为 any 可以解决任何问题,也可以解决任何问题
  • 哦,我明白了,另一种选择是使用 union - '|'并定义类型,如 'HTMLInputElement | HTML元素 |空'
  • @DenisMalykhin 不过,我们没有指定 dom 类型,它可以是 HTMLInputElement 或 HTMLDivElement 或 HTMLSVGElement ....
猜你喜欢
  • 2020-11-17
  • 2019-01-31
  • 2022-10-21
  • 2020-06-18
  • 2021-07-16
  • 2019-02-21
  • 2023-01-03
  • 1970-01-01
  • 2020-10-29
相关资源
最近更新 更多