ref를 활용하여 input 태그에 콜백함수로 가져온 엘리먼트를 담은 변수를 사용하여 DOM에 접근하기
constructor (props) {
super(props);
this.textInput = null;
}
constructor (props) {
super(props);
// 1. input 태그가 들어갈 공간(변수)
this.textInput = null;
// 2. ref 콜백함수를 통해 DOM에 접근
// 1) ref에 들어갈 함수 작성
this.setTextInputRef = (element) => {
// 2) element를 ref를 통해 DOM 가져옴
// 3) 저장해서 쓰기위해 만든 공간에 할당
this.textInput = element;
}
}
<input
type="text"
// 3. ref 속성을 이용해서 setTextInputRef를 호출
ref={this.setTextInputRef}
/>
textInputEvent = () => {
if(this.textInput) {
// ref를 통해서 DOM을 가져와서 그 안에 있는 내용에
// JS에서 id를 통해 가져온것 처럼 접근할 수 있다
this.textInput.focus();
}
}
위의 방법은 콜백함수를 이용하여 DOM을 조작하는 것이고
constructor (props) {
super(props);
// 16.3 버전 이후 사용가능
this.textInput = React.createRef();
}
console.log(this.myRef.current);