Skip to content

useRef

介绍

在 React 组件中获取/操作 DOM,需要使用 useRef 函数。

提示

类似于 vue 中的 ref 模板引用。

示例

tsx
import { useRef } from 'react'

function Refs() {
  const input = useRef < HTMLInputElement > null

  const handleClick = () => {
    console.log(input)
    input.current?.focus()
  }

  return (
    <>
      <input ref={input} />
      <button type="button" onClick={handleClick}>
        聚焦
      </button>
    </>
  )
}

export default Refs

基于 MIT 许可发布