React.js
21.03.30 함수형, 클래스형 컴포넌트에서의 props 사용 차이
슈팅스타제제
2021. 3. 30. 15:07
props란 ? 컴포넌트 속성을 나타내는 데이터!
함수 컴포넌트와 클래스 컴포넌트 모두 컴포넌트 자체 props를 수정해서는 안된다!!! 수정할 수 있는 것은 state이다.
props 를 다룰 때에는 순수함수처럼 동작해야 한다.
👉순수함수는 입력값을 바꾸지 않고 항상 동일한 입력값에 대해 동일한 결과를 반환하는 함수이다.
function pureFunc(a, b){
return a + b;
}
function notPureFunc(account, amount){
account.total -= amount;
return amount
}
📌함수형 컴포넌트
function Welcome(props){
return <h1>Hello, {props.name}</h1>
}
해도 되고
const Mycomponent = ({name}=>{
return (
<div>
안녕하세요. 제 이름은 {name}입니다. <br/>
</div>
)
})
와 같이 props를 불러올 필요 없이 바로 호출할 수 있다.
📌클래스형 컴포넌트
this.props 를 통해 값을 불러올 수 있다.
class Welcome extends React.Component{
render(){
return <h1>Hello, {this.props.name}</h1>
}
}
class Welcome extends React.Component{
render(){
const name = this.props.name;
return <h1>Hello, {name}</h1>
}
}