手动设置电流时,我在 useRef() 钩子上使用什么打字稿类型?

新手上路,请多包涵

如何使用 Typescript 将 React ref 用作可变实例?当前属性似乎被键入为只读。

我正在使用 React + Typescript 开发一个与不是由 React 呈现的输入字段交互的库。我想捕获对 HTML 元素的引用,然后将 React 事件绑定到它。

   const inputRef = useRef<HTMLInputElement>();
  const { elementId, handler } = props;

  // Bind change handler on mount/ unmount
  useEffect(() => {
    inputRef.current = document.getElementById(elementId);
    if (inputRef.current === null) {
      throw new Exception(`Input with ID attribute ${elementId} not found`);
    }
    handler(inputRef.current.value);

    const callback = debounce((e) => {
      eventHandler(e, handler);
    }, 200);

    inputRef.current.addEventListener('keypress', callback, true);

    return () => {
      inputRef.current.removeEventListener('keypress', callback, true);
    };
  });

它会产生编译器错误: semantic error TS2540: Cannot assign to 'current' because it is a read-only property.

我也试过 const inputRef = useRef<{ current: HTMLInputElement }>(); 这导致了这个编译器错误:

 Type 'HTMLElement | null' is not assignable to type '{ current: HTMLInputElement; } | undefined'.

  Type 'null' is not assignable to type '{ current: HTMLInputElement; } | undefined'.

原文由 JPollock 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 434
1 个回答

是的,这是打字方式的一个怪癖:

 function useRef<T>(initialValue: T): MutableRefObject<T>;
function useRef<T>(initialValue: T|null): RefObject<T>;

如果初始值包含 null ,但指定的类型参数没有,它将被视为不可变 RefObject

When you do useRef<HTMLInputElement>(null) , you’re hitting that case, since T is specified as HTMLInputElement , and null is inferred as HTMLInputElement | null

您可以通过以下方式解决此问题:

 useRef<HTMLInputElement | null>(null)

然后 THTMLInputElement | null ,它与第一个参数的类型匹配,所以你点击第一个覆盖并获得一个可变引用。

原文由 Retsam 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进