Skip to content

Instantly share code, notes, and snippets.

@lilywang711
Created July 30, 2020 06:47
Show Gist options
  • Save lilywang711/2b21fb8bb9c2c265fe0dc8ab24535424 to your computer and use it in GitHub Desktop.
Save lilywang711/2b21fb8bb9c2c265fe0dc8ab24535424 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