Skip to content

Instantly share code, notes, and snippets.

@khle
Forked from lilywang711/useImperativeHandle.tsx
Created October 22, 2021 15:49
Show Gist options
  • Save khle/33f6813f97c6a2f8eae506c527447202 to your computer and use it in GitHub Desktop.
Save khle/33f6813f97c6a2f8eae506c527447202 to your computer and use it in GitHub Desktop.
useImperativeHandle in typescript
// 定义
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