useAutoFocus.ts
import * as React from 'react';
export default function useAutoFocus<RefType extends HTMLElement>() {
const inputRef = React.useRef<RefType>(null);
React.useEffect(() => {
const node = inputRef.current;
if (node) {
node.focus();
}
}, []);
return inputRef;
}
使う側
function Hoge(props: Props) {
const [code, setCode] = React.useState('');
const inputRef = useAutoFocus<HTMLInputElement>();
return (
<TextInput
value={code}
onChange={(e) => setCode(e.target.value)}
ref={inputRef}
/>
);
}