🪁react/react 실습
useRef, useState 응용한 채팅앱기본 [자신감up 실습9]
하얀성
2024. 1. 29. 14:33
useRef()로 선언한 변수를 특정 태그에 가져다 쓰면 그걸 참조하도록 해주는 것
-구체적 과정-
- Ref 객체 생성: useRef()를 호출하여 생성된 ref 객체는 .current 속성을 가지고 있습니다. 이 ref 객체는 초기에 null로 설정됩니다.
- 태그에 Ref 연결: JSX에서, 해당 ref 객체를 특정 DOM 요소의 ref 속성에 할당합니다. 예를 들어, <input ref={myRef} />와 같이 사용할 수 있습니다.
- DOM 요소 참조: 할당된 후, React는 해당 DOM 요소에 대한 참조를 ref 객체의 .current 속성에 자동으로 할당합니다. 이를 통해 해당 DOM 요소에 프로그래밍 방식으로 접근할 수 있게 됩니다.
- 접근 및 조작: 이제 myRef.current를 통해 직접 DOM 요소에 접근하고, 필요에 따라 그 요소를 읽거나 조작할 수 있습니다.
렌더링 결과.
위는 엔터 제출 불가 + 제출 시 input창 초기화 x
아래는 엔터 제출 + 초기화 가능

구현 코드
function InputForm1() {
const [msg, setMsg] = useState();
const ref = useRef();
const hMessage = () => {
const text = ref.current.value;
setMsg(text);
};
return (
<div className="InputForm1">
<p>{msg}</p>
<input type="text" ref={ref} />
<button onClick={hMessage}>Send Message</button>
</div>
);
}
export default InputForm1;
import React, { useRef, useState } from "react";
function InputForm2() {
const [msg, setMsg] = useState();
const ref = useRef();
const hMessage = (e) => {
const text = ref.current.value;
setMsg(text);
e.preventDefault(); // 새로고침으로 form 제출값 날라가는 것 방지
ref.current.value = null; // input창의 ref 값을 없애줌
};
return (
<div className="InputForm2">
<form>
<p>{msg}</p>
<input type="text" ref={ref} />
<button onClick={hMessage}>Send Message</button>
</form>
</div>
);
}
export default InputForm2;