三、useRef() 的点点滴滴

380 阅读2分钟

1 useRef 作用

  1. 获取DOM元素的节点,获取子组件的实例
  2. 渲染周期之间共享数据的存储(state不能存储跨渲染周期的数据,因为state的保存会触发组件重渲染)

2 useRef 特性

useRef 返回一个可变的 ref 对象,其 .current 属性被初始化为传入的参数(initialValue)。返回的 ref 对象在组件的整个生命周期内保持不变。可以保存任何类型的值包括dom、对象等任何可辨值

const refContainer = useRef(initialValue);

ref 对象与自建一个 {current:""} 对象的区别是:useRef 会在每次渲染时返回同一个 ref 对象,即返回的 ref 对象在组件的整个生命周期内保持不变。自建对象每次渲染时都建立一个新的。

3 获取dom元素节点

const RefDemo = () => {
    const domRef = useRef(null)
    useEffect(() => {
      	// domRef.current 指向已挂载到 DOM 上的文本输入元素
        console.log("ref:deom-init", domRef, domRef.current)
    })
    return (
        <div>
            <div
                onClick={() => {
                    console.log("ref:deom", domRef, domRef.current)
                    domRef.current.focus()
                    domRef.current.value = "hh"
                }}
            >
                <label>这是一个dom节点</label>
                <input ref={domRef} />
            </div>
        </div>
    )
}

4 获取子组件实例

  • useImperativeHandle(ref,createHandle,[deps])可以自定义暴露给父组件的实例值。如果不使用,父组件的ref(chidlRef)访问不到任何值(childRef.current==null)

  • useImperativeHandle应该与forwradRef搭配使用

  • 因为函数组件没有实例。所以需要通过React.forwardRef会创建一个React组件,这个组件能够将其接受的ref属性转发到其组件树下的另一个组件中。

  • React.forward接受渲染函数作为参数,React将使用prop和ref作为参数来调用此函数。

const Child = forwardRef((props, ref) => {
    useImperativeHandle(ref, () => ({
        say: sayHello,
    }))
    const sayHello = () => {
        alert("hello,我是子组件")
    }
    return <h3>子组件</h3>
})
const RefDemo = () => {
    const childRef = useRef(null)
    useEffect(() => {
        console.log("ref:child-init", childRef, childRef.current)
    })
    const showChild = () => {
        console.log("ref:child", childRef, childRef.current)
        childRef.current.say()
    }
    return (
        <div style={{ margin: "100px", border: "2px dashed", padding: "20px" }}>
            <p onClick={showChild} style={{ marginTop: "20px" }}>
                这是子组件
            </p>
            <Child ref={childRef} />
        </div>
    )
}

5 渲染周期之间共享存储的数据

// 把定时器设置成全局变量使用useRef挂载到current上
import React, { useState, useEffect, useRef } from "react";
function App() {
  const [count, setCount] = useState(0);
  // 函数组件只要更新了,timer就会被重新为 null,所以函数组件需要借助useRef存储变量 
  // const timer = null
  
  // 把定时器设置成全局变量使用useRef挂载到current上
  const timer = useRef();
  
  // 首次加载useEffect方法执行一次设置定时器
  useEffect(() => {
    timer.current = setInterval(() => {
      setCount(count => count + 1);
    }, 1000);
  }, []);
  
  // count每次更新都会执行这个副作用,当count > 5时,清除定时器
  useEffect(() => {
    if (count > 5) {
      clearInterval(timer.current);
    }
  });
  return <h1>count: {count}</h1>;
}
export default App;