如何使用 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 许可协议
是的,这是打字方式的一个怪癖:
如果初始值包含
null
,但指定的类型参数没有,它将被视为不可变RefObject
。When you do
useRef<HTMLInputElement>(null)
, you’re hitting that case, sinceT
is specified asHTMLInputElement
, andnull
is inferred asHTMLInputElement | null
。您可以通过以下方式解决此问题:
然后
T
是HTMLInputElement | null
,它与第一个参数的类型匹配,所以你点击第一个覆盖并获得一个可变引用。