inputRef
사용 (callback ref)import React, { Component } from 'react';
class InputSomething extends Component {
const onFocus = () => {
this.inputRef.focus();
};
inputRef;
onInputRef = (c) => {
// createRef와는 다르게, 함수라서 다른 명령을 할 수 있는 자유도가 있음
// 다른 명령
this.inputRef = c
};
render() {
<div>
<input ref={this.onInputRef} />
<button onClick={onFocus}>Click!</button>
</div>
}
}
createRef
사용 - hooks 처럼 사용하기import React, { Component, createRef } from 'react';
class InputSomething extends Component {
const onFocus = () => {
this.inputRef.current.focus();
};
inputRef = createRef();
render() {
<div>
<input ref={this.inputRef} />
<button onClick={onFocus}>Click!</button>
</div>
}
}
useRef
사용import React, { useRef } from 'react';
const InputSomething = () => {
const onInputRef = useRef();
const onFocus = () => {
onInputRef.current.focus();
};
return (
<div>
<input ref={onInputRef} />
<button onClick={onFocus}>Click!</button>
</div>
)
};
참조: (1) React 기본 강좌 3-12. React.createRef - YouTube | ZeroCho TV