본문 바로가기

프론트앤드 수업

[react] props,state 값 받아오고 사용

728x90

const App = () => {
return
<div>
<Mycomponent name="green" age = "20">
children 속성 자리
</Mycomponent>
</div>
}

const MyComponent = ({name, age, children}) => {
return <div>
제 이름은 {name} 입니다.
제 나이는 {age} 입니다.
{children}
</div>
}

선언을 두번씩 할 필요없이 한번에 바로 받을 수 있다.

class Mycomponent extends Component {
const {name, age, children} = this.props;
render(
return()
)
}

기본값 받기
MyComponent.defaultProps ={
name : '기본이름',
age : 20,
}
받아오는 값의 타입을 설정할 수 있다. ( 타입 설정시 import를 해줘야 함)
import PropTypes from 'prop-types'; // 설정 후 사용가능
myComponent.propTypes = { // 객체의 속성은 p가 소문자
name : PropTypes.string // 프로퍼티의 타입설정에는 p가 대문자
}
종류: array(배열) string(문자) number(숫자) bool(true,false) func(함수) object(객체) any(아무 종류)
https://github.com/facebook/prop-types

* state 컴포넌트 내부에서 바뀔 수 있는 값. -> state가 변경되면 화면을 다시 그린다.
import { useState } from 'react'; // import로 useState를 걸어 준 후 사용이 가능하다.
const MyComState = () => {
const [countNum, setCountNum] = useState(0);
} // 해당형태로 작성이 가능하고 useState를 배열로 반환해준다. 배열의 0번째에는 상태(기본값)이 들어가있고, 배열의 1번째에는 값을 업데이트 할 수 있는 함수가 들어간 채로 반환됨
html이나 javascript처럼 바로 변경할 수 없고 setCountNum(20) 과 같은 방식으로 입력하면 값을 업데이트 할 수 있다.

함수형 컴포넌트
useState import
const [state, setState] = useState(초기값);

클래스 에서의 state사용
class MyComState extends Component {
state = {
countNum : 0,
}

render();{
const{ countNum } = this.state;
return(
<div>
<h1>{countNum}</h1>
<button onClick={() => { 
this.setState({countNum : countNum+1})}}
</div>
)
}
}
class형 컴포넌트
state 접근 this.state
state 변경 this.setState({})
constructor() 를 사용하지 않아도 됨

728x90
댓글