SPA(Single Page Application)
์น ํ์ด์ง๋ฅผ ์ฑ์ฒ๋ผ ๋์ํ๊ฒ ํ๋ค. (ํ์ด์ง ๊น๋นก์์ด ์๋ค.)
๋ฐ์ดํฐ์ ํ๋ฉด์ ์ผ์น์ํฌ ์ ์๋ค.
์ปดํฌ๋ํธํํ์ฌ ์ฌ์ฌ์ฉ์ด ๊ฐ๋ฅํ ์ฝํ ์ธ ๋ฅผ ์์ฑํ ์ ์๋ค.
html๋ฌธ์์์ ๊ธฐ๋ณธ์ ์ผ๋ก <div id="root"> </div>
๊ฐ ํ์ํ๋ค.
์ด๋ component๋ค์ด ๋ด๊ธธ ๋ถ๋ถ์ด๋ค.
์ฐ์ react๋ฅผ ์ค์นํ์ง ์๊ณ CDN๋ฐฉ์์ผ๋ก ๊ฐ์ ธ์ค๋๋ก ํ๋ค.
<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>
react
๋ javascript
๊ธฐ๋ฐ์ด๋ฏ๋ก <script>
์์ ์์ฑํ๋๋ก ํ๋ค.
const e = React.createElement;
class LikeButton extends React.Component {
constructor(props) {
super(props);
}
render() {
return e('button', { onClick: () => { console.log('clicked') }, type: 'submit' }, 'Like');
// --> <button type="submit">Like</button> ์ด๋ฐ ํ๊ทธ๋ฅผ ํ์ฑํ๊ฒ ๋ค.
}
}
React.createElement
๋ฅผ ๋ณ์์ ํ ๋นํ์ฌ component์ ์์ฑํ๋ค.
React.createElement( component, props, ...children )
// ์์๋๋ก 'HTML ์์', 'HTML ์์ฑ', 'text'์ ์์ฑํ๋ค.
'HTML ์์ฑ'์ ์์ฑํ ๋๋ camel case๋ก ์์ฑํ๋ค (onclick -> onClick)
component์ ๊ฐ์ ์ผ๋ก state(์ํ)๊ฐ ์๋ค.
์ example์์ ๋ง์ฝ Like
๊ธ์๊ฐ ๋ฐ๋๋ค๋ฉด Like
๊ฐ state
๊ฐ ๋๋ค.
์ฆ, ๋ฐ๋ ์ฌ์ง๊ฐ ์๋ ๋ถ๋ถ์ด state(์ํ)
์ด๋ค.
์ํ๋ this.state ={ }
๋ก ์์ฑํ๋ค.
๋ฐ๋ ์ํ๋ฅผ ํ๋ฉด์ ๋ฐ์ํ๋ ค๋ฉด render(){ }
์์์ ์์ฑํ๋ฉด ๋๋ค.
const e = React.createElement;
class LikeButton extends React.Component {
constructor(props) {
super(props);
this.state = {
liked: false, // <-- ๊ธฐ๋ณธ ์ํ
}
}
render() {
return e(
'button',
{ onClick: () => { this.setState({ liked: true }) }, type: 'submit' },
this.state.liked === true ? 'Liked' : 'Like'
);
// ํด๋ฆญ์ ํ๋ฉด true๋ก ๋ฐ๊ฟ์ค
}
}
this.state.liked
๊ฐ true
์ด๋ฉด button
์ text๋ฅผ Liked
๋ก ๋ฐ๊ฟ๋ผ.
์ฌ๊ธฐ์, classํ๋๊ฐ 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>
</head>
<body>
<div id="root"></div> <!-- ๊ฒฐ๊ณผ: <div id="root"><button>Like</button></div> -->
<script>
const e = React.createElement;
class LikeButton extends React.Component {
constructor(props) {
super(props);
this.state = {
liked: false, // <-- ๊ธฐ๋ณธ ์ํ
}
}
render() {
// return e('button', { onClick: () => { console.log('clicked') }, type: 'submit' }, 'Like');
// --> <button type="submit">Like</button> ์ด๋ฐ ํ๊ทธ๋ฅผ ํ์ฑํ๊ฒ ๋ค.
return e('button', { onClick: () => { this.setState({ liked: true }) }, type: 'submit' }, this.state.liked === true ? 'Liked' : 'Like');
// ํด๋ฆญ์ ํ๋ฉด true๋ก ๋ฐ๊ฟ์ค
}
}
</script>
<script>
ReactDOM.render(e(LikeButton), document.querySelector('#root'));
</script>
</body>
</html>