ReScript in Korean

useRef

원문

useRef 훅은 리액트 컴포넌트 내부에서 뮤터블 컨테이너를 생성하고 관리합니다.

사용법

let refContainer = React.useRef(initialValue);

React.useRefinitialValue 로 초기화 된 .current 레코드 필드를 포함한 참조 객체를 반환합니다. 이 객체는 변강 가능(mutable)합니다. 또한 컴포넌트의 수명(lifetime)동안 영속적입니다.

본질적으로, React.ref.current 레코드 필드에 변경 가능한 값을 저장할 수 있는 상자와 같습니다.

주로 DOM에 접근하는 방법으로 refs를 사용하는 편입니다. 만일 ref 객체를 <div ref={ReactDOM.Ref.domRef(myRef)} />로 리액트에 전달하면 리액트는 해당 노드가 변경될 때마다 해당 DOM 노드에 .current 필드 속성을 설정합니다.

그러나 useRef()는 ref 속성보다 더 유용합니다. useRef()는 클래스 인스턴스의 필드를 사용하는 것과 유사하게 뮤터블한 값을 유지하는데 편리합니다.

이렇게 동작하는 이유는 useRef()가 일반적인 자바스크립트 객체를 생성하기 때문입니다. useRef(){current: ...} 객체를 직접 만드는 것의 유일한 차이점은 useRef가 모든 렌더링에서 동일한 ref 객체를 제공한다는 것입니다.

useRef는 컨텐츠가 변경될 때 어떤한 것도 우리에게 알리지 않는다는 것을 알아두세요. .current 레코드 필드를 변형하는 것은 재 렌더링을 유발시키지 않습니다. 리액트가 DOM 노드에 ref를 연결하거나 떼어낼 때 (attaches or detaches) 어떤 코드를 실행하려면 여러분은 대신에 callback ref를 사용할 수 있습니다.

직접적인 DOM 조작에 대한 자세한 정보는 Refs and the DOM 페이지에서 찾을 수 있습니다.

예제

Text 인풋의 포커스 관리

/* TextInputWithFocusButton.re */
@send external focus: Dom.element => unit = "focus"
@react.component
let make = () => {
let inputEl = React.useRef(Js.Nullable.null)
let onClick = _ => {
inputEl.current
->Js.Nullable.toOption
->Belt.Option.forEach(input => input->focus)
}
<>
<input ref={ReactDOM.Ref.domRef(inputEl)} type_="text" />
<button onClick> {React.string("Focus the input")} </button>
</>
}

콜백 Ref의 사용

Refs and the DOM 섹션의 예제를 재사용합니다.

/* CustomTextInput.re */
@send external focus: Dom.element => unit = "focus"
@react.component
let make = () => {
let textInput = React.useRef(Js.Nullable.null)
let setTextInputRef = element => {
textInput.current = element;
}
let focusTextInput = _ => {
textInput.current
->Js.Nullable.toOption
->Belt.Option.forEach(input => input->focus)
}
<div>
<input type_="text" ref={ReactDOM.Ref.callbackDomRef(setTextInputRef)} />
<input
type_="button" value="Focus the text input" onClick={focusTextInput}
/>
</div>
}