作用:使用 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)