类型定义
types/react 类型定义中对useRef函数定义了三次(两次重载)
/**
* `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
*/
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
*/
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
*/
function useRef<T = undefined>(): MutableRefObject<T | undefined>;
第二个重载返回的RefObject 对象中current属性是只读属性
第一次定义
function useRef<T>(initialValue: T): MutableRefObject<T>;
如果函数调用匹配到这个定义,则 ref.current 类型只能是initialValue类型
初始值为boolean,没有传入T,则类型推断T为boolean,则始终只能是boolean类型
第二次定义(重载)
function useRef
(initialValue: T|null): RefObject ;
current值可以是T或者null 两种类型, 常见于获取dom元素
因为可能为null,所以确定存在,可以使用!非空断言
还有一种非空断言写法如此,Ref对象也改变了,从RefObject 变成MutableRefObject了
并且匹配到第一次定义(目前这个写法还没完全搞明白)
第三次定义(重载)
function useRef<T = undefined>(): MutableRefObject<T | undefined>;
自定义hook—useRefObject
import { useRef } from 'react'
export function useRefObject<T>(t: T) {
const ref = useRef<T>(t)
ref.current = t
return ref
}
使用这个hook,除了初始化useRef,每次render都会执行一遍ref.current = t, 那它的应用场景就应该是current值依赖别的状态。
比如说,依赖到props值,当props值变化时,也要同步改变。正常要使用useEffect
const ref = useRef(props.parmas1)
useEffect(() => {
ref.current = props.parmas1
}, [props.params1])
但是使用useRefObject 就可以省略useEffect.