0403 - React Ref:DOM

solda-blue·2023년 4월 3일
0

React

목록 보기
1/1

ref를 활용하여 input 태그에 콜백함수로 가져온 엘리먼트를 담은 변수를 사용하여 DOM에 접근하기

1. constructor 안에 element를 할당할 변수를 선언

constructor (props) {
	super(props);
    this.textInput = null;
}

2. ref를 통해 element를 들고올 콜백함수를 만든다

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;
        }
    }

3. 가져올 태그의 속성에 ref를 추가하고 2에서 만든 콜백함수를 입력한다

<input
    type="text"
	// 3. ref 속성을 이용해서 setTextInputRef를 호출
	ref={this.setTextInputRef}
/>

4. 가져온 element를 조작하기 -> input 태그에 focus주기

textInputEvent = () => {
	if(this.textInput) {
   		// ref를 통해서 DOM을 가져와서 그 안에 있는 내용에
    	// JS에서 id를 통해 가져온것 처럼 접근할 수 있다
    	this.textInput.focus();
	}
}

!textInput을 배열로 만들고 push() 나 concat() 으로 할당하면 하나의 변수에 여러 element를 담을 수 있다

위의 방법은 콜백함수를 이용하여 DOM을 조작하는 것이고

React 16.3 버전 이상부터는 createRef()라는 내장 함수를 이용하여 변수에 할당 할 수 있다

constructor (props) {
	super(props);
    // 16.3 버전 이후 사용가능
    this.textInput = React.createRef();
}

! createRef를 사용할 땐 해당 변수의 뒤에 .current를 입력해야 사용할 수 있다 ex=>

console.log(this.myRef.current);

0개의 댓글