반응형

React에서 컴포넌트를 다루는 props와 state라는 2가지 데이터가 있습니다.
이 2가지의 데이터에 대해서 간단하게 소개드리겠습니다.
1. props
- 우선 컴포넌트 ExampleComp.js를 새로 작성합니다.
// ExampleComp.js
import React from 'react';
const ExampleComp = (props) => {
return (
<div>
<h1>저는 올해 {props.age}살인 {props.name}입니다.</h1>
</div>
);
}
export default ExampleComp;- 그리고 App.js에서 ExampleComp를 추가해서 ExampleComp안에 매개변수 name과 age에 값을 입력해 줍니다.
// App.js
import React from 'react';
import ExampleComp from './ExampleComp';
class App extends React.Component {
render(){
return (
<ExampleComp name="sangmin" age="30" />
);
}
}
export default App;결과적으로 다음과 같이 화면에 출력이 됩니다.
저는 올해 30살인 sangmin입니다.2. state
state값이 변경되면 컴포넌트가 다시 랜더링이 됩니다. 이 같은 동작으로 저희는 동적인 페이지를 작성할 수 있습니다.
- 카운팅을 하는 Count.js를 작성해봅시다.
// Count.js
import React from 'react';
class counter extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
this.updateCount=this.updateCount.bind(this);
}
updateCount(){
this.setState({
count: this.state.count+1
});
}
render() {
return (
<div>
<h1>카운트 = {this.state.count}</h1>
<button onClick={this.updateCount}>카운트 세기</button>
</div>
);
}
}
export default counter;
참고 사이트 : devjeon1358님의 블로그
반응형