公式サイトに載っているサンプルになります。
1 2 3 4 5 6 7 8 9 10 11 12 13 |
function TextInputWithFocusButton() { const inputEl = useRef(null); const onButtonClick = () => { // `current` points to the mounted text input element inputEl.current.focus(); }; return ( <> <input ref={inputEl} type="text" /> <button onClick={onButtonClick}>Focus the input</button> </> ); } |
input要素のref属性にuseRefで宣言した値を設定します。そうすることでinput要素への関連付けをすることが可能です。
要は、ソース内のinputElという変数経由でinput要素へのアクセスが可能になります。
この記事へのコメントはありません。