์ด์ ๊ณผ ๊ฐ์ ๋ฐฉ์(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 )
}
}
์ฌ๊ธฐ์ ๋ฌธ์ ๋ 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์ฅ์
<!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>