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