Created
July 30, 2020 06:47
-
-
Save lilywang711/2b21fb8bb9c2c265fe0dc8ab24535424 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