๋ชฉํ: ์ ์ฅ ๋ฒํผ์ ํด๋ฆญํ์ ๋ ์ ์์ ์ผ๋ก ์ ๋ ฅ๋์ง ์์์ผ๋ฉด focusํ๊ธฐ
โ ์ ์์ ์ผ๋ก ์ ๋ ฅ๋์ง ์์ element์ ์ ๊ทผํ๊ธฐ
useRef
: React.MutableRefObject๋ฅผ ๋ฐํํจ. HTML ์์์ ์ ๊ทผํ ์ ์๋ ๊ธฐ๋ฅ.
const DiaryEditor = () => {
const authorInput = useRef();
const contentsInput = useRef();
const handleSubmit = () =>{
if(state.author.length < 1){
authorInput.current.focus();
// ref๊ฐ authorInput์ธ ํ๊ทธ์ ์ ๊ทผ -> current๋ก ํ์ฌ ํ๊ทธ ๊ฐ์ ธ์ด
return; // ๋์ด์ ์งํ ์๋๋๋ก ๋์ ๋๋
}
if(state.contents.length < 3){
contentsInput.current.focus();
return;
}
alert('์ ์ฅ ์ฑ๊ณต!');
}
return <div className="DiaryEditor">
<h2>์ค๋์ ์ผ๊ธฐ</h2>
<div>
<input ref={authorInput} />
</div>
<div>
<textarea ref={contentsInput} />
</div>
const authorInput = useRef();
๋ ํผ๋ฐ์ค ๊ฐ์ฒด ์์ฑ<input ref={authorInput} />
์ง์ผ๋ณผ ์์์ ref ์์ฑ ์ถ๊ฐauthorInput.current
ํ์ฌ ์์ ๋ถ๋ฌ์ดfocus();
์ํ๋ ์ด๋ฒคํธ ์ถ๊ฐhttps://inf.run/qAuJ
ํ์ ํฌ๊ธฐ๋ก ์๋ผ ๋จน๋ ๋ฆฌ์กํธ(React.js) : ๊ธฐ์ด๋ถํฐ ์ค์ ๊น์ง by ์ด์ ํ Winterlood