-
-
Save khle/33f6813f97c6a2f8eae506c527447202 to your computer and use it in GitHub Desktop.
useImperativeHandle in typescript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 定义 | |
export interface MyInputHandles { | |
focus(): void; | |
} | |
const MyInput: RefForwardingComponent<MyInputHandles, MyInputProps> = ( | |
props, | |
ref | |
) => { | |
const inputRef = useRef<HTMLInputElement>(null); | |
useImperativeHandle(ref, () => ({ | |
focus: () => { | |
if (inputRef.current) { | |
inputRef.current.focus(); | |
} | |
}, | |
})); | |
return <input {...props} ref={inputRef} />; | |
}; | |
export default forwardRef(MyInput); | |
// 使用 | |
import MyInput, { MyInputHandles } from './MyInput'; | |
const Autofocus = () => { | |
const myInputRef = useRef<MyInputHandles>(null); | |
useEffect(() => { | |
if (myInputRef.current) { | |
myInputRef.current.focus(); | |
} | |
}); | |
return <MyInput ref={myInputRef} /> | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment