如何在 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'.