React | HOC

eommoonjooยท2022๋…„ 6์›” 26์ผ
1

Intro ๐ŸŒผ

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)์ด๊ฒŒ ์ƒ์†Œํ•ด์„œ ๊ทธ๋ ‡์ง€...๊ทธ๋ ‡๊ฒŒ ์–ด๋ ต์ง€ ์•Š๋‹ค.
ํ•˜๋‹ค๋ณด๋ฉด ๋œ๋‹ค. ๊ทธ๋ƒฅ ํ•˜๋ฉด ๋จ.

profile
์„ธ์ƒ๊ณผ ์†Œํ†ต์„ ๊ฟˆ๊พธ๋Š” ๊ฐœ๋ฐœ์ž

0๊ฐœ์˜ ๋Œ“๊ธ€