2023. 6. 16. 22:03ㆍReact
import ReactDOM from 'react-dom'
// 리액트 컴포넌트 => htmlelement 연결하기
import React from 'react';
// 리액트 컴포넌트 만들기
ReactDOM.render(
<HelloMessage name="Taylor" />.
document.getElementById('hello-example')
//이걸 통해서 얻어온 html 앨리먼트(실제 DOM) 에 이 컴포넌트를 그려라 라는 의미
);
class HelloMessage extends React.Component { //리액트 컴포넌트
render() {
return (
<div>
Hello {this.props.name}
</div>
);
}
}
ReactDOM.render
어떤 컴포넌트를 실제로 웹에 표현하기 위해선 실제 어던 HTML 앨리먼트에 이 컴포넌트를 그리라는 행위를 해야하고, 이 행위가 시작지점이다.
ReactDOM.render. 를 마치 메인처럼 생각하면 좋다.(프로그램의 시작함수)
- index.html 파일 생성
- cdn 링크 속 태그 추가(개발용)
- 객체 만들어진 것 확인하기
- <script type="text/javascript"> console.log(React); console.log(ReactDOM); </script>
개발자도구를 열어 확인하면 객체가 두가지 생긴것을 볼 수 있다.
리액트 이전의 프론트엔드
리액트 없이 DOM 을 만들어보자.
<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">
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Example</title>
<style>
* {
margin: 0;
padding: 0;
border: 0;
}
#root p {
color: white;
font-size: 20px;
background-color: green;
text-align: center;
width: 200px;
}
#btn_plus {
background-color: red;
border: 2px solid #000000;
font-size: 15px;
width: 200px;
}
</style>
</head>
먼저, head 부분에 위와 같이 style 태그를 작성한다.
<div id = "root"></div>
<button id="btn_plus">+</button>
먼저, head 부분에 위와 같이 style 태그를 작성한다.
const root = document.querySelector("#root"); // id 가 root 인 것을 가져옴
const btn_plus = document.querySelector('#btn_plus');
직접 DOM 을 생성해준다. 해석해보면 ID가 root , btn_plus 인 것을 가져온다는 뜻이다. 위에서 선언한 두 아이디를 가진 것을 가져왔다고 보면 된다.
let i = 0;
root.innerHTML = '<p>init : 0</p>' // 위의 p 스타일을 받음
btn_plus.addEventListener('click', () => {
root.innerHTML = `<p>init : ${++i}`;
});
직접 DOM 을 생성해준다. 해석해보면 ID가 root , btn_plus 인 것을 가져온다는 뜻이다. 위에서 선언한 두 아이디를 가진 것을 가져왔다고 보면 된다.
<!DOCTYPE html>
<html lang="en">
<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">
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Example</title>
<style>
* {
margin: 0;
padding: 0;
border: 0;
}
#root p {
color: white;
font-size: 20px;
background-color: green;
text-align: center;
width: 200px;
}
#btn_plus {
background-color: red;
border: 2px solid #000000;
font-size: 15px;
width: 200px;
}
</style>
</head>
<body>
<div id = "root"></div>
<button id="btn_plus">+</button>
<script crossorigin src="https://unpkg.com/react@18/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
<script type="text/javascript">
// console.log(React);
// console.log(ReactDOM);
const root = document.querySelector("#root"); // id 가 root 인 것을 가져옴
const btn_plus = document.querySelector('#btn_plus');
let i = 0;
root.innerHTML = '<p>init : 0</p>' // 위의 p 스타일을 받음
btn_plus.addEventListener('click', () => {
root.innerHTML = `<p>init : ${++i}`;
});
</script>
</body>
</html>
컴포넌트를 활용한 프론트엔드
위에 작성했던 body 부분은 모두 주석처리 후 진행한다.
const component = {
message: 'init' ,
count: 0,
render() {
return `<p>${this.message} : ${this.count}</p>`;
}
};
컴포넌트 생성. 컴포넌트라고 하는 것 안에는 데이터가 들어있다. 이 데이터들의 값은 항상 바뀔 수 있다. 바뀌는걸 알려주는 것이 render() 이다.
function render(rootElement , component) {
rootElement.innerHTML = component.render();
}
//초기화
render(document.querySelector('#root'), component);
document.querySelector('#btn_plus').addEventListener('click', () => {
component.message = 'update' ;
component.count = component.count + 1;
render(document.querySelector('#root'), component);
//값이 변경될때마다 렌더를 해줘야 됨. 이것을 편하게 해주는게 바로 리액트
});
render 함수를 작성해주고, 버튼을 클릭할때마다 1씩 업데이트를 해주는데 업데이트가 되기 전 초기화, 또 업데이트가 될 때마다 render 과정이 필요한 것을 볼 수 있다. 이걸 간편하게 해주는것이 바로 react 이다.
리액트 사용
- 리액트의 역할
- 실제 DOM 에 컴포넌트를 연결하는 일
const Component = props => {
return React.createElement('p', null, `${props.messege} : ${props.count}`);
// 외부에서 props가 받은 메세지와 카운터를p태그의 가운데에 들어가는 값으로 표현하겠다는 정의
// 리액트의 앨리먼트로 리턴되어야 함.
}//리액트 컴포넌트
외부에서 props 가 받은 메세지와 카운터를 p 태그의 가운데에 들어가는 값으로 표현하겠다는 정의
ReactDOM.render(React.createElement
(Component, {messege: 'init' , count: 0}, null) ,document.querySelector('#root')
); //하나는 리액트 컴포넌트 , 하나는 컴포넌트가 그려지는 곳
React.createElement 가 리액트 컴포넌트 , root 라는 아이디를 가진 곳이 컴포넌트가 그려지는 곳
document.querySelector('#btn_plus').addEventListener('click', function() {
ReactDOM.render(React.createElement(Component, {messege: 'update' , count: 10}, null)
,document.querySelector('#root') );
});
만약 한번 클릭시 숫자 10으로 바뀌게 하고싶다면 이 코드를 추가하면 됨,
'React' 카테고리의 다른 글
[React] Hooks 알아보기 ( useState , useEffect ) (0) | 2023.06.23 |
---|---|
StyledComponents(버튼) 알아보기 ! (0) | 2023.06.22 |
Style Loader (classNames) 알아보기 ! (0) | 2023.06.22 |
props 와 state (0) | 2023.06.16 |
React Component (1) | 2023.06.16 |