useInperativeHandle是通过ref暴露子组件中的方法
1.场景说明-直接调用子组件内部的方法
import { forwardRef, useImperativeHandle, useRef } from "react"// 子组件const Son = forwardRef((props, ref) => {// 实现聚焦逻辑const inputRef = useRef(null)const focusHandler = () => {inputRef.current.focus()}// 把聚焦方法暴露出去useImperativeHandle(ref, () => {return {// 暴露的方法focusHandler}})return <input type="text" ref={inputRef} />
})// 父组件
function App () {const sonRef = useRef(null)const focusHandler = () => {console.log(sonRef.current)sonRef.current.focusHandler()}return (<><Son ref={sonRef} /><button onClick={focusHandler}>focus</button></>)
}export default App