React - useImperativeHandle

suaxi
2026-04-13 / 0 评论 / 3 阅读 / 正在检测是否收录...

作用:通过 ref 讲子组件的方法暴露给父组件

import { forwardRef, useImperativeHandle, useRef } from 'react'

const Son = forwardRef((props, ref) => {
  const inputRef = useRef(null)
  const inputHandle = () => {
    inputRef.current.focus()
  }

  useImperativeHandle(ref, () => {
    return {
      inputHandle
    }
  })
  return <input type="text" ref={inputRef} />
})

function App() {
  const sonRef = useRef(null)
  const sonInputFocusHandle = () => {
    console.log(sonRef)
    sonRef.current.inputHandle()
  }

  return (
    <div className="App">
      <Son ref={sonRef} />
      <button onClick={sonInputFocusHandle}>focus</button>
    </div>
  )
}

export default App
0

评论 (0)

取消