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