HOC...
React ๊ณต์๋ฌธ์ ๋ค์ด๊ฐ๋ฉด ์ค๋ช
์ด ์์ฃผ ์๋์ด ์์ง...
๊ทผ๋ฐ, ๋๋ง์ ๋ฐฉ์์ผ๋ก ์ดํดํ๋๊ฒ ํ์ํ๋๊น~
์ฌ์ค ์ ์์ด๋ค...
๊ฐ๋ ์์ฃผ ๊ฐ๋ ์ฐ๋๋ฐ... ๋ก์ง์ด ๋ฐ๋ณต๋๋ ์ปดํฌ๋ํธ๊ฐ ๋ง์ ๊ฒฝ์ฐ์ ์ด๋ค. ์ฌ์ค ๊ทธ๊ฒ๋ hook์ผ๋ก ๋นผ์ ์ฌ์ฉํ๋ค๋ณด๋ฉด, ๊ทธ๊ฒ๋ ๊ฑฐ์ ์์ฐ๊ฒ ๋์ง๋ง...
Test.js
import React from "react";
import withLoading from "./withLoading";
const TestPage = (props) => {
return <div>TesPage</div>;
};
export default withLoading(TestPage);
Test2.js
import React from "react";
import withLoading from "./withLoading";
const Test2Page = (props) => {
return <div style={{border:"1px solid red"}}>Tes2Page</div>;
};
export default withLoading(TestPage);
๋๊ฐ์ ์ปดํฌ๋ํธ๊ฐ ์๋ค๊ณ ๊ฐ์ ํ์ ๋,(Test.js, Test2.js) ์ด๋ฆ์์๋ ๋๊ปด์ง๋ฏ์ด ๋ก์ง์ ๊ฐ์๋ฐ, ํ๋ฉด์ด ๋ค๋ฅผ ์ ์๋ ๊ฒฝ์ฐ๊ฐ ์๋ค. ์ด๋ด๋ HOC๊ฐ ๊ฐ ๊ฟํ ์ด๋ค.
const withLoading = (WrappedComponent) => (props) => {
// ์ฌ๊ธฐ์ ๋ก์ง ์ฒ๋ฆฌํด์ค~props ๋ฐ์์~
return <WrappedComponent {...props} />;
};
export default withLoading;
๋ณดํต HOC๋ฅผ ์ฌ์ฉํ๋ฉด with๋ฅผ ๋ถ์ฌ์ ์ฌ์ฉํ๋ค.
์ฌ์ฉ๋ฐฉ๋ฒ์ ์ฌ๋ฌ๊ฐ์ง์ธ๋ฐ, TestPage๋ก props๋ฅผ ์๋์ฒ๋ผ ๋๊ฒจ๋ ๋๊ณ ,
import React from "react";
import "./App.css";
import TestPage from "./components/TestPage";
function App() {
return <TestPage type={"test"} />;
}
export default App;
์๋๋ฉด ํด๋น์ปดํฌ๋ํธ์์ ์๋์ฒ๋ผ url๋ฅผ ๋ฐ~๋ก ๋๊ธธ์๋ ์๋ค.
const withLoading = (WrappedComponent, url) => (props) => {
console.log("type", props.type); //์ฌ๊ธฐ์ ๋ก์ง์ ์ฒ๋ฆฌํด์ผ ํจ.
console.log("url", url);
return <WrappedComponent {...props} />;
};
export default withLoading;
import React from "react";
import withLoading from "./withLoading";
const TestPage = (props) => {
return <div style={{ border: "1px solid red" }}>TesPage</div>;
};
export default withLoading(TestPage, "url");
์ด๊ฒ ๊ตฌ์กฐ๊ฐ...App.js์์ TestPage๋ก props๋ฅผ ๋๊ธธ ๋, withLoading์ ๊ฑฐ์ณ์ Test.js ๋ก ๋๊ธด๋ค๊ณ ๋ณด๋ฉด ๋๋ค. ๊ทธ๋์ ๊ด๋ จ ๋ก์ง๋ค์ withLoading์์ ์ฒ๋ฆฌํด๋ TestPage์ ๋ฐ์ ํ ์ ์๋ค.
TestPage(App.js) => withLoading(TestPage) => TestPage.js
์ฌ์ค... (WrappedComponent) => (props)
์ด๊ฒ ์์ํด์ ๊ทธ๋ ์ง...๊ทธ๋ ๊ฒ ์ด๋ ต์ง ์๋ค.
ํ๋ค๋ณด๋ฉด ๋๋ค. ๊ทธ๋ฅ ํ๋ฉด ๋จ.