Ref를 사용하면 특정 DOM노드나 React 요소에 접근하는 방법을 제공해준다.
Ref 생성하기
아래와 같이 React.createRef()
함수로 Ref를 생성한뒤, 원하는 DOM 노드의 프로퍼티로 Ref를 지정해주면된다.
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.myRef = React.createRef();
}
render() {
return <div ref={this.myRef} />;
}
}
Ref에 접근하기
ref에 엘리먼트가 전달되었을 때, ref의 current
라는 어트리뷰트에 담기게된다.
const node = this.myRef.current;
그 뒤에는 해당 컴포넌트에 있는 함수를 호출 할 수 있다.
class AutoFocusTextInput extends React.Component {
constructor(props) {
super(props);
this.textInput = React.createRef();
}
componentDidMount() {
this.textInput.current.focusTextInput();
}
render() {
return (
<CustomTextInput ref={this.textInput} />
);
}
}