Skip to content

Latest commit

 

History

History
50 lines (35 loc) · 1.33 KB

05. ref.md

File metadata and controls

50 lines (35 loc) · 1.33 KB

ref

: 리액트 프로젝트 내부에서 DOM에 이름을 다는 것.
	
  DOM을 직접적으로 건드려야할 때 사용됨.  e.g. 특정 input에 포커스 주기, 스크롤 박스 조작하기, Canvas 요소에 그림 그리기 등 

콜백 함수를 통한 ref 설정

ref를 달고자 하는 요소에 ref 라는 콜백 함수를 props로 전달해줌.

이 콜백함수는 ref 값을 파라미터로 받고, 함수 내부에서 파라미터로 받은 ref를 컴포넌트의 멤버변수로 설정해줌.

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

this.input은 input 요소의 DOM을 가리킴.

createRef를 통한 ref 설정

컴포넌트 내부에서 멤버 변수로 React.createRef()를 담아주고, 해당 멤버 변수를 ref를 달고자 하는 요소에 ref prop로 넣어줌.

ref를 설정해 준 DOM에 접근하려면 this.input.current를 조회함.

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

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

컴포넌트에 ref 달기

컴포넌트 내부에 있는 DOM을 컴포넌트 외부에서 사용할 때 쓰임.

<My Component 
	ref = {(ref) => {this.myComponent=ref}}
/>