Ref란?
일부 구성 요소가 참조한 데이터를 하위 항목에게 전달하는 기능입니다.
Ref를 사용할 때
- input/textarea 등에 포커스를 해야 할 때
- 특정 DOM의 크기를 가져와야 할 때
- 특정 DOM에서 스크롤 위치를 가져오거나 설정을 해야 할 때
- 외부 라이브러리를 사용 할 때
1. ref 전달하기
// FancyButton.js
const FancyButton = React.forwardRef((props, ref) => (
<button ref={ref} className="FancyButton">
{props.children}
</button>
));
import FancyButton from './FancyButton';
const ref = React.createRef();
render() {
return (
<FancyButton ref={ref}>Click me!</FancyButton>;
)
}
직접적인 부모-자식간이 아닌, ref 를 자식에게 전달해 자식의 요소를 부모가 참조하는 방법입니다.
위 예제에서는 React.forwardRef를 사용하여 ref가 전달된 FancyButton.js 파일을 가져온 다음 클래스에 ref를 할당할 변수를 만들고 createRef()로 초기화합니다. 그리고 나서 render()에서 button에 ref를 전달합니다.
2. 콜백 ref
class CustomTextInput extends React.Component {
constructor(props) {
super(props);
this.textInput = null;
this.setTextInputRef = element => {
this.textInput = element;
};
this.focusTextInput = () => {
// DOM API를 사용하여 text 타입의 input 엘리먼트를 포커스합니다.
if (this.textInput) this.textInput.focus();
};
}
componentDidMount() {
// 마운트 되었을 때 자동으로 text 타입의 input 엘리먼트를 포커스합니다.
this.focusTextInput();
}
render() {
// text 타입의 input 엘리먼트의 참조를 인스턴스의 프로퍼티
// (예를 들어`this.textInput`)에 저장하기 위해 `ref` 콜백을 사용합니다.
return (
<div>
<input
type="text"
ref={this.setTextInputRef}
/>
<input
type="button"
value="Focus the text input"
onClick={this.focusTextInput}
/>
</div>
);
}
}
각각의 content 는 key 를 가지고 있고 content 마다 ref 를 설정하려고 합니다. content 가 dictionary 또는 array 형식으로 온다면 반복문을 사용해서 처리하겠죠. createRef() 로는 처리하기 어렵습니다. 콜백 ref를 써서 각 content 별로 ref 를 설정하고 key 를 통해 설정한 ref 에 접근할 수 있도록 했습니다.
ref => {
this.contents[key] = ref;
}
ko.reactjs.org/docs/forwarding-refs.html
Forwarding Refs – React
A JavaScript library for building user interfaces
ko.reactjs.org
tech.osci.kr/2019/10/10/82068584/
React에서 Ref 사용하기
React는 컴포넌트 트리 선언과 props 사용을 통해서, DOM 노드에 레퍼런스를 걸지 않고도 UI 제어가 대부분 가능합니다. 하지만 개발 중에는 특정 노드에 레퍼런스를 걸고 접근해야할 경우도 가끔��
tech.osci.kr
리액트에서 DOM 에 직접적인 접근을 할 때, ref | VELOPERT.LOG
ref 알아보기 리액트 개발을 하다보면 DOM 에 직접적인 접근을 해야 할 때가 있습니다. 그럴 때는 ref 라는것을 사용합니다. 그런데 정확히 어떠한 상황에 DOM 에 직접적인 접근이 필요할까요? 필요�
velopert.com
'React' 카테고리의 다른 글
useState를 사용한 배열 set (0) | 2020.09.22 |
---|---|
객체를 사용한 style 작성 (0) | 2020.09.22 |
[React 스터디] 4: Context (0) | 2020.09.03 |
[React 스터디] 3 : 코드 분할 (0) | 2020.08.31 |
숫자만 입력 가능하게 하기 (0) | 2020.08.31 |
댓글