createRef
createRef
๋ ์์์ ๊ฐ์ ํฌํจํ ์ ์๋ ref ๊ฐ์ฒด๋ฅผ ์์ฑํฉ๋๋ค.
class MyInput extends Component {
inputRef = createRef();
// ...
}
์ฐธ์กฐ
createRef()
ref๋ฅผ ํด๋์ค ์ปดํฌ๋ํธ ์์ ์ ์ธํ๋ ค๋ฉด createRef
๋ฅผ ํธ์ถํฉ๋๋ค.
import { createRef, Component } from 'react';
class MyComponent extends Component {
intervalRef = createRef();
inputRef = createRef();
// ...
์๋์์ ๋ ๋ง์ ์์ ๋ฅผ ๋ณผ ์ ์์ต๋๋ค.
๋งค๊ฐ๋ณ์
createRef
๋ ๋งค๊ฐ๋ณ์๋ฅผ ๋ฐ์ง ์์ต๋๋ค.
๋ฐํ๊ฐ
createRef`๋ ๋จ์ผ ์์ฑ์ ๊ฐ์ง ๊ฐ์ฒด๋ฅผ ๋ฐํํฉ๋๋ค.
current
: ์ฒ์์๋null
๋ก ์ค์ ๋ฉ๋๋ค. ์ด๋ฅผ ๋์ค์ ๋ค๋ฅธ ๊ฒ์ผ๋ก ์ค์ ํ ์ ์์ต๋๋ค. ref ๊ฐ์ฒด๋ฅผ JSX ๋ ธ๋์ref
์ดํธ๋ฆฌ๋ทฐํธ๋ก React์ ์ ๋ฌํ๋ฉด React๋ ์ด๋ฅผcurrent
ํ๋กํผํฐ๋ก ์ค์ ํฉ๋๋ค.
์ฃผ์
createRef
๋ ํญ์ ๋ค๋ฅธ ๊ฐ์ฒด๋ฅผ ๋ฐํํฉ๋๋ค. ์ด๋{ current: null }
์ ์ง์ ์์ฑํ๋ ๊ฒ๊ณผ ๊ฐ์ต๋๋ค.- ํจ์ ์ปดํฌ๋ํธ์์๋ ํญ์ ๋์ผํ ๊ฐ์ฒด๋ฅผ ๋ฐํํ๋
useRef
๋ฅผ ๋์ ์ฌ์ฉํ ์ ์์ต๋๋ค. const ref = useRef()
๋const [ref, _] = useState(() => createRef(null))
์ ๋์ผํฉ๋๋ค.
์ฌ์ฉ
ํด๋์ค ์ปดํฌ๋ํธ์์ ref ์ ์ธํ๊ธฐ
ํด๋์ค ์ปดํฌ๋ํธ๋ด์์ ์ฐธ์กฐ๋ฅผ ์ ์ธํ๋ ค๋ฉด createRef
๋ฅผ ํธ์ถํ๊ณ ๊ทธ ๊ฒฐ๊ณผ๋ฅผ ํด๋์ค ํ๋์ ํ ๋นํฉ๋๋ค.
import { Component, createRef } from 'react';
class Form extends Component {
inputRef = createRef();
// ...
}
์ด์ ref={this.inputRef}
๋ฅผ JSX์ ์๋ <input>
์ ์ ๋ฌํ๋ฉด, React๋ this.inputRef.current
๋ฅผ input DOM ๋
ธ๋๊ฐ ์ฐจ์งํ๊ฒ ํฉ๋๋ค. ์๋ฅผ ๋ค์ด input์ ํฌ์ปค์ฑํ๋ ๋ฒํผ์ ๋ง๋๋ ๋ฐฉ๋ฒ์ ๋ค์๊ณผ ๊ฐ์ต๋๋ค.
๋์
createRef
๋ฅผ ์ฌ์ฉํ๋ ํด๋์ค์์ useRef
๋ฅผ ์ฌ์ฉํ๋ ํจ์๋ก ๋ง์ด๊ทธ๋ ์ด์
ํ๊ธฐ
์๋ก์ด ์ฝ๋๋ฅผ ์์ฑํ๋ค๋ฉด ํด๋์ค ์ปดํฌ๋ํธ ๋์ ํจ์ ์ปดํฌ๋ํธ๋ฅผ ์ฌ์ฉํ๋ ๊ฒ์ ์ถ์ฒํฉ๋๋ค. createRef
๋ฅผ ์ฌ์ฉํ๋ ๊ธฐ์กด ํด๋์ค ์ปดํฌ๋ํธ๊ฐ ์๋ ๊ฒฝ์ฐ, ์ด๋ฅผ ๋ณํํ๋ ๋ฐฉ๋ฒ์ ๋ค์๊ณผ ๊ฐ์ต๋๋ค. ๋ค์์ ์๋ณธ ์ฝ๋์
๋๋ค.
์ด ์ปดํฌ๋ํธ๋ฅผ ํด๋์ค์์ ํจ์๋ก ๋ณํํ๋ ค๋ฉด, createRef
ํธ์ถ์ useRef
ํธ์ถ๋ก ๋ฐ๊ฟ์ค๋๋ค.