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>;


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM