手动设置电流时,我使用 useRef() 钩子的打字稿类型是什么? [英] What typescript type do I use with useRef() hook when setting current manually?

查看:27
本文介绍了手动设置电流时,我使用 useRef() 钩子的打字稿类型是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 Typescript 中使用 React ref 作为可变实例?当前属性的类型似乎是只读的.

How can I use a React ref as a mutable instance, with Typescript? The current property appears to be typed as read-only.

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

I am using React + Typescript to develop a library that interacts with input fields that are NOT rendered by React. I want to capture a reference to the HTML element and then bind React events to it.

  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);
    };
  });

它生成编译器错误:语义错误 TS2540:无法分配给当前",因为它是只读属性.

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

I also tried const inputRef = useRef<{ current: HTMLInputElement }>(); This lead to this compiler error:

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

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

推荐答案

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

Yeah, this is a quirk of how the typings are written:

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

如果初始值包含null,但指定的类型参数不包含,则将其视为不可变的RefObject.

If the initial value includes null, but the specified type param doesn't, it'll be treated as an immutable RefObject.

当您执行 useRef(null) 时,您遇到了这种情况,因为 T 被指定为 HTMLInputElement,并且null 被推断为 HTMLInputElement |null.

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

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

You can fix this by doing:

useRef<HTMLInputElement | null>(null)

那么 T 就是 HTMLInputElement |null,它匹配第一个参数的类型,因此您点击第一个覆盖并获得可变引用.

Then T is HTMLInputElement | null, which matches the type of the first argument, so you hit the first override and get a mutable ref instead.

这篇关于手动设置电流时,我使用 useRef() 钩子的打字稿类型是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆