React hooks - useRef

用法

useRef 函数返回一个可变的 ref 对象,该对象只有一个 current 属性。可以在调用 useRef 函数时为其指定初始值。并且这个返回的 ref 对象在组件的整个生命周期内保持不变。

// 1. 导入 useRef
import { useRef } from 'react'
// 2. 调用 useRef 创建 ref 对象
const refObj = useRef(初始值)
// 3. 通过 ref.current 访问 ref 中存储的值
console.log(refObj.current)
特点
  1. 获取 DOM 元素或子组件的实例对象
import React, { useRef } from 'react'

export const InputFocus: React.FC = () => {
  // 1. 创建 ref 引用
  const iptRef = useRef<HTMLInputElement>(null) // 加上泛型引用后就可以提示代码了

  const getFocus = () => {
    // 3. 调用 focus API,让文本框获取焦点
    iptRef.current?.focus() // iptRef.current可能为空,后面使用链式调用?.来保证不报错
  }

  return (
    <>
      {/* 2. 绑定 ref 引用 */}
      <input type="text" ref={iptRef} />
      <button onClick={getFocus}>点击获取焦点</button>
    </>
  )
}
  1. 存储渲染周期之间共享的数据
export const Counter: React.FC = () => {
  const [count, setCount] = useState(0)
  const prevCountRef = useRef<number>() // 默认值为 undefined,泛型为number,将来要存number类型的值
  let preCount // 创建一个变量存储旧值无法实现,因为每次count发生变化时组件重新渲染导致preCount初始化为undefined
  const add = () => {
    setCount((c) => c + 1)
    prevCountRef.current = count // 记录旧值到prevCountRef中
    // preCount = count // 错误写法,无法实现
  }
  return (
    <>
      <h1>新值是:{count},旧值是:{prevCountRef.current} </h1>
      <button onClick={add}>+1</button>
    </>
  )
}
注意事项
  1. 组件rerender(重新渲染)时useRef不会被重复初始化
  2. ref.current发生变化时不会造成组件的rerender(重新渲染)
  3. ref.current不能作为其他hooks(useMemo、useCallback、useEffect 等) 的依赖项
    组件首次渲染后会触发一次 useEffect 。但当time.current 变化不会触发 useEffect 的重新执行。
export const RefTimer: React.FC = () => {
  const time = useRef(Date.now())
  const updateTime = () => {
    time.current = Date.now()
  }
  useEffect(() => {
    console.log('time 的值发生了变化:' + time.current)
  }, [time.current])

  return (
    <>
      <h3>时间戳是:{time.current}</h3>
      <button onClick={updateTime}>给ref赋新值</button>
    </>
  )
}
  • 7
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值