๐ย Reference
๐ Chapter
โฃ
โฃ
key
ย prop์ ๋ค ์ ์๋ค.ย ref
ย prop๋ ๋ง์ฐฌ๊ฐ์ง๋ก HTML ์๋ฆฌ๋จผํธ ์ ๊ทผ์ด๋ผ๋ ํน์ํ ์ฉ๋๋ก ์ฌ์ฉ๋๊ธฐ ๋๋ฌธ์ ์ผ๋ฐ์ ์ธ prop์ผ๋ก ์ฌ์ฉ์ ํ ์ ์๋ค.ref
ย prop์ ์ฌ์ฉํ๋ ค๋ฉด React์์ ์ ๊ณตํ๋ย forwardRef()
๋ผ๋ ํจ์๋ฅผ ์ฌ์ฉํด์ผ ํ๋ค.forwardRef
๋ผ๋ ํจ์๋ก ๊ฐ์ธ์ฃผ๋ฉด, ํด๋น component๋ ํจ์๋ฅผ ๋ ๋ฒ์งธ ๋งค๊ฐ ๋ณ์๋ก ๊ฐ๊ฒ ๋๋๋ฐ, ์ด๋ฅผ ํตํด ์ธ๋ถ์์ย ref
ย prop์ ๋๊ธธ ์ ์๋ค.React.forwardRef
๋ฅผ ์ฌ์ฉํ๋ฉด ๋ฐ์ ์ ์๋ค. forwardRef
๋ ์์ component์์ ์ ๋ฌ ๋ฐ์ ref๋ฅผ ํ์ component๋ก ์ ๋ฌํ๋ ์ญํ ์ ๋งก๋๋ค. ์ด ํจ์๋ React.ReactNode
ํ์
์ ๋ฐํํ๊ธฐ ๋๋ฌธ์ ์ผ๋ฐ function component์ ๋์ผํ๊ฒ JSX ๋ฌธ๋ฒ์ ์จ์ ๋ ๋๋ง ํ ์ ์๋ค.์์ 1
import React, { forwardRef, useRef } from "react";
const Input = forwardRef((props, ref) => {
return <input type="text" ref={ref} />;
});
function Field() {
const inputRef = useRef(null);
function handleFocus() {
inputRef.current.focus();
}
return (
<>
<Input ref={inputRef} />
<button onClick={handleFocus}>์
๋ ฅ๋ ํฌ์ปค์ค</button>
</>
);
}
์์ 2
import React from "react";
const FancyButton = React.forwardRef((props, ref) => (
<button ref={ref} className="FancyButton">
{props.children}
</button>
));
// You can now get a ref directly to the DOM button:
const ref = React.createRef();
<FancyButton ref={ref}>Click me!</FancyButton>;