簡體   English   中英

typescript - 關於 React typescript useRef 的問題

[英]typescript - Question about React typescript useRef

目標是制作一個影響 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 類型不適合這種情況。

仔細查看錯誤消息: Type 'HTMLElement | null' is not assignable to type 'HTMLInputElement | null'. Type 'HTMLElement | null' is not assignable to type 'HTMLInputElement | null'. . 正確的類型,根據消息是HTMLInputElement | null HTMLInputElement | null 此外,稍微改變useFocus是有意義的:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM