React useRef

Sujeong Kยท2022๋…„ 9์›” 10์ผ
0

React

๋ชฉ๋ก ๋ณด๊ธฐ
3/5

๐Ÿ“Œ React์—์„œ DOM ์กฐ์ž‘ํ•˜๊ธฐ

๋ชฉํ‘œ: ์ €์žฅ ๋ฒ„ํŠผ์„ ํด๋ฆญํ–ˆ์„ ๋•Œ ์ •์ƒ์ ์œผ๋กœ ์ž…๋ ฅ๋˜์ง€ ์•Š์•˜์œผ๋ฉด 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(); ์›ํ•˜๋Š” ์ด๋ฒคํŠธ ์ถ”๊ฐ€

Studying...

https://inf.run/qAuJ
ํ•œ์ž… ํฌ๊ธฐ๋กœ ์ž˜๋ผ ๋จน๋Š” ๋ฆฌ์•กํŠธ(React.js) : ๊ธฐ์ดˆ๋ถ€ํ„ฐ ์‹ค์ „๊นŒ์ง€ by ์ด์ •ํ™˜ Winterlood

profile
์ฐจ๊ทผ์ฐจ๊ทผ ์ฒœ์ฒœํžˆ

0๊ฐœ์˜ ๋Œ“๊ธ€