React Hooks 之 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
     */
    // TODO (TypeScript 3.0): <T extends unknown>
    function useRef<T>(initialValue: T): MutableRefObject<T>;

    // convenience overload for refs given as a ref prop as they typically start with a null value
    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
    function useRef<T = undefined>(): MutableRefObject<T | undefined>;

什么是Ref(引用)

参考Kotlin中的ObjectWrapper。

useRef用法

var ref = React.useRef(88);
ref.current += 1; // 该修改被应用到之后的视图渲染中!但是很明显,这种修改不会触发组件渲染

return <div>{ref.current}</div>;

posted @ 2021-01-12 18:04  develon  阅读(611)  评论(0编辑  收藏  举报