// 리액트를 다루는 기술 3장
✔️함수형 컴포넌트
import React from 'react';
function App() {
const name = '리액트';
return (
<div className = "react">{name}</div>
);
}
export default App;
장점
단점
✔️클래스형 컴포넌트
import React, {Component} from 'react';
class App extends Component {
render() { // render함수 꼭 존재해야함!!
const name = "react";
return <div className = "react"> {name}</div>;
}
}
export default App;
import React from 'react';
import MyComponent from './MyComponent';
const App = () => {
return <MyComponent/>;
}
export default App;
props란?
properties를 줄인 표현으로 props 값은 해당 컴포넌트를 불러와 사용하는 부모 컴포넌트에서 설정할 수 있음
import React from 'react';
const MyComponent = props => {
return <div> 안뇽 내 이름은 {props.name}야 </div>;
}
export default MyComponent;
import React from 'react';
import MyComponent from './MyComponent';
const App = () => {
return <MyComponent name = "민서"/>;
}
export default App;
name 값이 지정되지 않았을 경우 defalutProps로 설정
근데 난 이게 적용이 안 됨...도대체 왜..? 짱나.... 쓰라는 고대로 썼는데 왜 안 돼...
children이란?
컴포넌트 태그 사이의 내용을 보여주는 props
내보내지는 모듈의 태그 사이에 내용 작성 = props.children
import React from 'react';
const MyComponent = props => {
return (
<div>
안뇽 내 이름은 {props.name}야 <br/>
children 값은 {props.children}입니다.
</div>
) ;
};
MyComponent.defalutProps = {
name : '기본 이름'
};
export default MyComponent;
import React from 'react';
import MyComponent from './MyComponent';
const App = () => {
return <MyComponent>민지</MyComponent>
}
export default App;
위 코드를 비구조화 할당 문법을 통해 작성할 수도 있음
방법 1
import React from 'react';
const MyComponent = props => {
const {name, children} = props;
return (
<div>
안뇽 내 이름은 {name}야 <br/>
children 값은 {children}입니다.
</div>
) ;
};
MyComponent.defalutProps = {
name : '기본 이름'
};
export default MyComponent;
방법 2 : 함수 파라미터 부분에서 바로 사용
import React from 'react';
const MyComponent = ({name, children}) => {
return (
<div>
안뇽 내 이름은 {name}야 <br/>
children 값은 {children}입니다.
</div>
) ;
};
MyComponent.defalutProps = {
name : '기본 이름'
};
export default MyComponent;
propTypes란?
: 컴포넌트의 필수 props를 지정하거나 props의 타입을 지정할 때 사용
import React from 'react';
import PropTypes from 'prop-types';
const MyComponent = ({name, children}) => {
return (
<div>
안뇽 내 이름은 {name}야 <br/>
children 값은 {children}입니다.
</div>
) ;
};
MyComponent.defalutProps = {
name : "기본 이름"
};
MyComponent.propTypes = {
name: PropTypes.string
};
export default MyComponent;
propTyeps를 통해 name을 string으로 지정해주었음
이렇게 할 경우 name을 string이 아닌 형태로 지정할 경우 출력은 제대로 되지만 콘솔창에서 오류가 뜸
isRequired를 이용하여 필수 props를 지정할 수도 있음
import React from 'react';
import PropTypes from 'prop-types';
const MyComponent = ({name, children, favoriteNum}) => {
return (
<div>
안뇽 내 이름은 {name}야 <br/>
children 값은 {children}입니다.<br/>
제일 좋아하는 숫자는 {favoriteNum}이야
</div>
) ;
};
MyComponent.defalutProps = {
name : "기본 이름"
};
MyComponent.propTypes = {
name: PropTypes.string,
favoriteNum : PropTypes.isRequired
};
export default MyComponent;
지정하지 않았을 경우 콘솔창에서 오류 뜸!
이 외에 많은 PropTypes종류가 있음
( 리액트를 다루는 기술 책 참고 )
state란?
: 컴포넌트 내부에서 바뀔 수 있는 값
props는 부모 컴포넌트에서만 바뀔 수 있는 반면 state는 부모가 아닌 현재 컴포넌트에서 직접 바꿀 수 있음!
1️⃣ 클래스형 컴포넌트의 state
컴포넌트에 state를 설정할 때는 constructor메서드를 작성하여 설정함
constructor 를 작성할 때는 반드시 super(props)를 호출해야함
import React , {Component} from 'react';
class Counter extends Component {
constructor(props) {
super(props);
// state의 초깃값 설정하기
this.state = {
number: 0
};
}
render() {
const {number} = this.state // state를 조회할 때는 this.state로 조회함
return (
<div>
<h1>{number}</h1>
<button
onCLick = {() => {
this.setState({number : number + 1});
}}
// onClick을 통해 버튼이 클릭되었을 때 호출할 함수를 지정
// this.setState를 사용하여 state에 새로운 값 넣을 수 있음
>
+1
</button>
</div>
);
}
}
export default Counter;
state의 초깃값은 반드시 객체 여야함
constructor 메서드를 선언하지 않고 state 설정하는 방식도 있음!
class Counter extends Component {
state = {
number: 0
}
(...)
}
⬆️이게 더 간단하고 보기 좋은듯
setState를 사용하여 값을 업데이트 하고 난 다음에 특정 작업을 하고 싶을 때는 setState의 두번째 파라미터로 콜백함수를 등록하면 됨
(...)
<button
onClick = {() => {
this.setState({number : number + 1},
() => {console.log(this.state)}
);
(...)
2️⃣ 함수형 컴포넌트에서 useState사용
Hooks 사용!
사용하기 전에 배열 비구조화 할당이란? 밑 코드 같은거
const array = [1,2];
const one = array[0];
const two = array[1];
// 이걸 배열 비구조화 할당 형식으로 바꾸면
const array = [1,2];
const [one, two] = array;
// 이렇게 깔끔하게 바뀜
useState 함수의 인자에서 상태의 초깃값을 넣어줌
초깃값이 반드시 객체일 필요 없음! 숫자, 문자열, 객체, 배열 다 가능!
import React, { useState } from 'react';
const Say = () => {
const [message, setMessage] = useState('');
// 첫 번째 원소는 현재 상태, 두 번째 원소는 상태를 바꾸어 주는 함수(setter 함수)
const onClickEnter = () => setMessage('안뇽!');
const onClickLeave = () => setMessage('잘 가!');
return (
<div>
<button onClick = {onClickEnter}>입장</button>
<button onClick = {onClickLeave}>퇴장</button>
<h1>{message}</h1>
</div>
)
}
export default Say;
위 코드는 처음 현재 상태에 아무것도 넣지 않았음 useState의 괄호 안에 무언가를 써주면 페이지의 처음 화면엔 그 문구가 뜰 거임
한 컴포넌트에서 useState 여러번 사용도 가능함!
[React] Hooks: useState, useEffect, useReducer (0) | 2022.05.31 |
---|---|
[React] map과 filter를 통한 배열 관리 (0) | 2022.04.28 |
리액트를 다루는 기술 11장 (0) | 2021.01.21 |
리액트를 다루는 기술 10장 (0) | 2021.01.21 |
리액트를 다루는 기술 9장 (0) | 2021.01.17 |