ReactJS - ref : DOM

ROCKBELL·2022년 12월 5일

리액트

목록 보기
7/13

ref

ref 사용해야 하는 경우

DOM을 꼭 직접적으로 건드려야 할 때

  • 특정 input에 focus 주기
  • 스크롤 박스 조작하기
  • Canvas 요소에 그림그리기

ref 사용 방법

콜백함수를 통한 ref 설정 방법

<input ref={(ref) => {this.input = ref}} />

createRef를 통한 ref 설정 방법

class RefSample extends Component {
	input = React.createRef();

    handleFocus = () => {
    	this.input.current.focus();
    }
    
    render() {
    	return(
        	<input ref={this.input} />
        )
    }
}

export default RefSample;

ref를 이용하여 컴포넌트 내부 메서드 호출

// App.jsx
class App extends Component {
  	render() {
    	return(
          <>
        	<ScrollBox 
				ref={this.scrollBox = ref}
              />
             /*
              초기 렌더링시 this.scrollBox 값은 undefined
              화살표 함수를 이용해 메서드를 실행하면
              버튼을 누르는 시점에서 this.scrollBox.scrollBottom 값을 가져올 수 있음
            */
            <button onClick={onClick={() => this.scrollBox.handleScroll()}}>맨 아래로</button>
            </>
        )
    }
}
// ScrollBox.jsx

class ScrollBox extends Component {
   
   scrollToBottom = () => {
    const { scrollHeight, clientHeight } = this.box;
      /* 앞 코드에는 비구조화 할당 문법을 사용했습니다.
      다음 코드와 같은 의미입니다.
      const scrollHeight = this.box.scrollHeight;
      const clientHeight = this.box.cliengHeight;
      */
      this.box.scrollTop = scrollHeight - clientHeight;
    };
  
	render(){
        const style = {
          border: "1px solid black",
          height: "300px",
          width: "300px",
          overflow: "auto",
          position: "relative",
        };
        const innerStyle = {
          width: "100%",
          height: "650px",
          background: "linear-gradient(white, black)",
        };
    	return(
        	<>
              <div style={style} ref={(ref) => this.box = ref}>
                <div style={innerStyle}>
                </div>
              </div>
            </>
        )
    }
}

함수형 컴포넌트에서 ref 사용

Hook 함수의 useRef 메서드를 사용하여 Reaact.createRef 와 유사

0개의 댓글