 ()를 통해 사용.(클래스형은 잘 사용하지 않으므로 참고만 하자)
ref를 사용한다.(1) 콜백 함수
ref를 props로 전달받아 컴포넌트의 멤버 변수로 설정한다.import React, { Component } from "react";
export default class RefClass1 extends Component {
handleFocus = () => {
// this : RefClass1 컴포넌트
console.log(this);
this.myInput.focus();
};
render() {
return (
<div>
<p>(클래스형 컴포넌트) 버튼 클릭 시 input에 focus 처리</p>
<input
type="text"
ref={(ref) => {
this.myInput = ref;
}}
/>
<button onClick={this.handleFocus}>focus</button>
</div>
);
}
}
(2) React.createRef()
React.createRef()를 사용해 ref를 생성하고, DOM 요소를 참조한다.this.refName.current로 참조한다.import React, { Component, createRef } from "react";
export default class RefClass2 extends Component {
// createRef를 사용해서 만들 때는 컴포넌트 내부에서 변수에 React.createRef()를 담아주어야 함
myInput = createRef();
handleFocus = () => {
// DOM 요소 선택 시 this.myInput.current 까지 접근
this.myInput.current.focus();
};
render() {
return (
<div>
<p>(클래스형 컴포넌트) 버튼 클릭 시 input에 focus 처리</p>
<input type="text" ref={this.myInput} />
<button onClick={this.handleFocus}>focus</button>
</div>
);
}
}
useRef())useRef()는 Hook 중 하나로, DOM 요소나 변수를 참조하기 위해 사용한다.ref.current 속성으로 값에 접근한다.// 1. ref 객체 만들기
const myRef = useRef();
// 2. 선택하고 싶은 DOM에 ref값으로 설정
<element ref={myRef}></element>
// 3. useRef()로 만든 객체 안의 current가 실제 요소를 가르킴
myRef.current;(1) DOM 요소에 접근
useRef()를 사용해 DOM 요소를 참조하고 직접 조작할 수 있다.document.querySelector()와 비슷한 역할을 수행한다.import React, { useRef } from "react";
export default function RefFunction1() {
// 1. ref 객체 만들기
const inputRef = useRef(null);
const handleFocus = () => {
// 3. useRef()로 만든 객체의 current 값에 focus() DOM API사용
// *focus() : 지정된 html 요소에 포커스 설정
inputRef.current.focus();
};
return (
<div>
<p>(함수형 컴포넌트) 버튼 클릭 시 input에 focus 처리</p>
{/* 2. 선택하고 싶은 DOM에 ref prop 설정 */}
<input type="text" ref={inputRef} />
<button onClick={handleFocus}>focus</button>
</div>
);
}
(2) 로컬 변수로 사용
useRef()는 랜더링 간에 값을 유지할 수 있어 로컬 변수로 사용할 수 있다.import React, { useRef, useState } from "react";
export default function RefFunction2() {
const idRef = useRef(1);
const [id, setId] = useState(10);
let test = 10;
const plusIdRef = () => {
idRef.current += 1;
console.log(idRef.current);
test += 1;
console.log(test);
};
const plusIdState = () => {
setId(id + 1);
};
return (
<div>
<h1>Ref Sample</h1>
<h2>{test}</h2>
<h2>{idRef.current}</h2>
<button onClick={plusIdRef}>PLUS Ref</button>
<h2>{id}</h2>
<button onClick={plusIdState}>PLUS State</button>
</div>
);
}
id를 사용하면 중복될 수 있으나, ref는 컴포넌트 내부에서만 유효하여 중복 문제가 없다.ref는 필요한 경우에만 사용해야 한다.alert 지양: UX 측면에서 alert는 사용하지 않는 것이 권장되며, 대신 ref로 입력창에 포커스를 주는 방식이 더 사용자 친화적이다.
내가 이 text에다가 문자를 입력하지 않고 focus버튼을 누른다면 알람이 뜨는것이 아니라 text에 포커스가 가서 text를 무조건 쳐야 한다는 느낌을 줌.