TypeScript useRef 使用问题

本文探讨了在TypeScript中使用useRef钩子时遇到的current属性不可写的问题,并提供了解决方案,通过调整泛型参数使其变为可变。
部署运行你感兴趣的模型镜像

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
     */

您可能感兴趣的与本文相关的镜像

ACE-Step

ACE-Step

音乐合成
ACE-Step

ACE-Step是由中国团队阶跃星辰(StepFun)与ACE Studio联手打造的开源音乐生成模型。 它拥有3.5B参数量,支持快速高质量生成、强可控性和易于拓展的特点。 最厉害的是,它可以生成多种语言的歌曲,包括但不限于中文、英文、日文等19种语言

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

RI Code

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值