import { useState, useRef } from 'react';

function Ref() {
    const { text, setText } = useState('');
    const textRef = useRef();
    // == 는 String Type을 비교한다.
    // === 는 object type을 비교한다. ===를 쓸 것!
    const handleChange = (e, option) => {
        if (option === 1) {
            textRef.current.value = e.target.value;
            setText(e.target.value);
        } else if (option === 2) {
            setText(textRef.current.value);
        }
    }

    return (
        <div>
            <input type="text" value={text} onChange={(e) => handleChange(e, 1)} />
            <br />
            <textarea
                rows={5}
                cols={30}
                ref={textRef}
                onChange={(e) => handleChange(e, 2)}
            ></textarea>

            <button>Ref Info</button>
        </div>
    )
}

onChange에 화살표 함수를 꼭 써야하는 경우에는 이렇게 매개변수를 통해 또 다른 조작을 해야할 경우이다. 

만약 (e) => handleChange(e, 2)가 없으면 해당 이벤트가 정상 동작하지 않음.

 

useRef 를 import하면 직접적으로 돔요소를 건들여야할 때 쓰이는 ref를 통해 이름을 달 수 있다.

 

+ Recent posts