React - forwardRef

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

作用:使用 ref 暴露组件给父节点

import { forwardRef, useRef } from 'react'

// function Son() {
//   return <input type="text" />
// }

const Son = forwardRef((props, ref) => {
  return <input type="text" ref={ref} />
})

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

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

export default App
0

评论 (0)

取消