TypeScript useRef 使用问题

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
     */
  • 6
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值