当前位置: 代码迷 >> 综合 >> TypeScript useRef 使用问题
  详细解决方案

TypeScript useRef 使用问题

热度:25   发布时间:2023-12-14 06:04:32.0

TypeScript useRef 使用问题

interface IModalReturn {destroy: () => void;update: (newConfig: ModalFuncProps) => void;
}let confirmModalRef = useRef<IModalReturn>(null);confirmModalRef.current = Modal.confirm({title: '确认删除吗?',content: '...',onOk() {}
});

在书写上面代码时,ts会给出错误提示 Cannot assign to 'current' because it is a read-only property. ,因为 current 为只读属性,故而不能赋值。

那么怎么将 current 属性转为 动态可变 的呢?

其实在 useRef 的类型定义中已经给出了答案

function useRef<T>(initialValue: T): MutableRefObject<T>;// convenience overload for refs given as a ref prop as they typically start with a null value/*** `useRef` returns a mutable ref object whose `.current` property is initialized to the passed argument* (`initialValue`). The returned object will persist for the full lifetime of the component.** Note that `useRef()` is useful for more than the `ref` attribute. It’s handy for keeping any mutable* value around similar to how you’d use instance fields in classes.** Usage note: if you need the result of useRef to be directly mutable, include `| null` in the type* of the generic argument.** @version 16.8.0* @see https://reactjs.org/docs/hooks-reference.html#useref*/

其中注意下面这句话

Usage note: if you need the result of useRef to be directly mutable, include | null in the type of the generic argument.

如果需要直接修改useRef的结果,则在泛型参数的类型中包含 | null 就可以了

let confirmModalRef = useRef<IModalReturn | null>(null);

这样就变为动态可变的,不会再给出报错提示

useRef 在类型定义中具有多个重载声明,最初的代码走的便是下面的声明

function useRef<T>(initialValue: T|null): RefObject<T>;// convenience overload for potentially undefined initialValue / call with 0 arguments// has a default to stop it from defaulting to {} instead/*** `useRef` returns a mutable ref object whose `.current` property is initialized to the passed argument* (`initialValue`). The returned object will persist for the full lifetime of the component.** Note that `useRef()` is useful for more than the `ref` attribute. It’s handy for keeping any mutable* value around similar to how you’d use instance fields in classes.** @version 16.8.0* @see https://reactjs.org/docs/hooks-reference.html#useref*/
  相关解决方案