[REACT] JSX์™€ BABEL

poseassomeยท2022๋…„ 1์›” 13์ผ
0

REACT

๋ชฉ๋ก ๋ณด๊ธฐ
2/3
post-thumbnail

๐Ÿ“Ž JSX

์ด์ „๊ณผ ๊ฐ™์€ ๋ฐฉ์‹(React.createElement ์‚ฌ์šฉ)์œผ๋กœ ์ž‘์„ฑํ•˜๋ฉด ์ฝ”๋“œ๊ฐ€ ๋ณต์žกํ•ด์ง€๊ธฐ ๋•Œ๋ฌธ์— ์ข€ ๋” ์‰ฝ๊ฒŒ ์ž‘์„ฑํ•˜๋„๋กํ•œ๋‹ค.

HTML๋ฌธ๋ฒ•๊ณผ ๋˜‘๊ฐ™์ด <button>์„ ๋‹ค์‹œ ์ž‘์„ฑํ•˜๊ณ  const e๋ฅผ ์‚ญ์ œํ•œ๋‹ค.
ReactDOM.render ๋ถ€๋ถ„๋„ e()๋ฅผ ์ง€์šฐ๊ณ  <LikeButton />์œผ๋กœ ์ž‘์„ฑํ•œ๋‹ค.

class LikeButton extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      liked: false,     // <-- ๊ธฐ๋ณธ ์ƒํƒœ
    }
  }

  render() {
    return <button type="submit" onClick={() => { this.setState({ liked: true }) }}>{this.state.liked === true ? 'Liked' : 'like'}</button>
    // JSX ( JS + XML )
  }
}

๐Ÿ“Ž BABEL

์—ฌ๊ธฐ์„œ ๋ฌธ์ œ๋Š” React๋Š” HTML๋ฌธ๋ฒ•์„ ์ง€์›ํ•ด์ฃผ์ง€ ์•Š๊ธฐ ๋•Œ๋ฌธ์— BABEL์ด ํ•„์š”ํ•˜๋‹ค.

BABEL CDN์„ ์ถ”๊ฐ€ํ•˜๊ณ  <script> type์„ ์ž‘์„ฑํ•œ๋‹ค.
๊ทธ๋Ÿฌ๋ฉด ์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ ์•ˆ์—์„œ HTML๋ฌธ๋ฒ•์„ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค.

BABEL์ด JSX๋ฌธ๋ฒ•์„ React.createElement๋กœ ๋ณ€ํ™˜ํ•ด์ค€๋‹ค.

<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
<script type="text/babel"> </script>

์—ฌ๊ธฐ์„œ ์‚ฌ์šฉํ•˜๋Š” ๋ฌธ๋ฒ•์ด JSX์ด๋‹ค
์ปจํ…์ธ  ๋ถ€๋ถ„์— ์ค‘๊ด„ํ˜ธ{ }๋ฅผ ๊ฐ์‹ธ์ฃผ๋ฉด ๊ทธ ์•ˆ์—์„œ ์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ ์ฝ”๋“œ๋ฅผ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค.

๋งŒ์•ฝ <Likebutton />์„ 4๊ฐœ๋ฅผ ์“ฐ๊ณ ์‹ถ๋‹คํ•˜๋ฉด ์ถ”๊ฐ€ํ•œ ๋งŒํผ ์•Œ์•„์„œ ๋‚ด์šฉ์ด ์ฑ„์›Œ์ง„๋‹ค. ==> component์žฅ์ 
react_component


๐Ÿ“‘ ์ „์ฒด ์ฝ”๋“œ

<!DOCTYPE html>
<html lang="ko">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>์ปดํฌ๋„ŒํŠธ ์ƒ์„ฑ</title>
  <script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script>
  <script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>
  <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
</head>

<body>
  <div id="root"></div> <!-- ๊ฒฐ๊ณผ: <div id="root"><button>Like</button></div> -->
  <script type="text/babel">
    class LikeButton extends React.Component {
      constructor(props) {
        super(props);
        this.state = {
          liked: false,     // <-- ๊ธฐ๋ณธ ์ƒํƒœ
        }
      }

      render() {
        return <button type="submit" onClick={() => { this.setState({ liked: true }) }}>{this.state.liked === true ? 'Liked' : 'like'}</button>
        // JSX ( JS + XML )
      }
    }
  </script>
  <script type="text/babel">
    // ReactDOM.render(<LikeButton />, document.querySelector('#root'));
    ReactDOM.render(<div><LikeButton /><LikeButton /></div>, document.querySelector('#root'));
  </script>
</body>

</html>
profile
Frontend Developer

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