개발일지
개발일지 12일차
index.ys
2023. 3. 19. 01:47
리액트 찍어먹기
- 리액트는 현재 프론트엔트 기술중 가장 사용성이 높은 자바스크립트 프레임워크이다.
리액트 컴포넌트(Component)
- 앱을 이루는 최소한의 단위이다.
- 컴포넌트의 이름은 대문자로 시작한다 ex) <Button />, <Header />
- 컴포넌트는 재사용성이 높다.
컴포넌트의 종류
함수형 컴포넌트 정의하기
- 데이터는 가진 하나의 props 객체인자를 받은후 엘리먼트를 반환한다.
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
클래스형 컴포넌트 정의하기
class Welcome extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
컴포넌트 렌더링
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
const root = ReactDOM.createRoot(document.getElementById('root'));
const element = <Welcome name="Sara" />;
root.render(element);
<Welcome name="Sara" />가 컴포넌트이다
function Welcome(props) { //컴포넌트 호출
return <h1>Hello, {props.name}</h1>; //props.name = Sara 출력
}
const root = ReactDOM.createRoot(document.getElementById('root'));
const element = <Welcome name="Sara" />; //Welcome 컴포넌트, props:{name: 'Sara'}
root.render(element);const element = <Welcome name="Sara" />;
리액트 프롭스(Props)
- Props는 상위 컴포넌트에서 하위 컴포넌트로 데이터를 전달해준 객체이다.
- 컴포넌트는 그릇, Props는 그릇에 담기는 음식이라고 생각하면 된다. 그릇은 똑같지만 그릇에 담기는 음식들은 바뀔 수 있다.
프롭스 정의하기
import React from 'react';
function Prob(props) {
return (
<div>
<main>
<h1>안녕하세요. {props.name} 입니다.</h1>
</main>
</div>
);
}
export default Main;
컴포넌트 호출
import React, { Component } from 'react';
import Header from './component/Prob';
function App() {
return (
<div>
<Prob name="짱구"/> //<h1>안녕하세요. {props.name}(짱구) 입니다.</h1>
</div>
);
}
export default App;
리액트 스테이트(State)
import React, { useState } from 'react';
function Example() {
// "count"라는 새 상태 변수를 선언합니다
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
useState가 훅이다. Hook을 호출해 함수 컴포넌트 안에 state를 추가했다.
state는 컴포넌트가 리렌더링 되어도 그대로 유지된다. 이벤트핸들러나 다른곳에서 호출 할 수 있다.
useState는 인자로 초기 state 값을 하나 받는다.
하나의 컴포넌트 안에서 여러개의 State 사용
function ExampleWithManyStates() {
// 상태 변수를 여러 개 선언했습니다!
const [age, setAge] = useState(28);
const [fruit, setFruit] = useState('apple');
const [todos, setTodos] = useState([{ text: 'Hello world' }]);
// ...
}
리액트의 존재에 대해 예전부터 알고 있었지만 이제야 첫걸음을 뗀다, 머리가 복잡해지기 않기위해 리액트공부를 미뤄왔으나 이제는 조금씩 공부하고 이해가 되지않는 부분은 반복적으로 공부하여 기초를 다져야 겠다.