티스토리 뷰
728x90
# state
state란 변경될 수 있는 값을 의미합니다. 리액트에서 state에는 두가지가 있습니다.
먼저, 클래스형 컴포넌트가 가지고 있는 state에 대해 알아봅시다.
컴포넌트 생성자 메서드인 constructor()를 이용하여 state를 설정할 수 있습니다. 이때, 반드시 super(props)를 호출해 주어야 합니다.
class Counter extends Component{
constructor(props) {
super(props);
this.state = {
num : 0
};
}
render(){
const {num} = this.state;
return (
<div>
<h1><strong>COUNTER</strong></h1>
<h2>{num}</h2>
<button onClick={ () => {
this.setState({num : num + 1});
}}>증가</button>
</div>
);
}
}
또 다른 방법은 constructor()가 있는 자리에 객체 형태로 state를 직접 추가해줄 수 있습니다.
state = {
num : 0
};
두번째는 함수형 컴포넌트에서 useState()를 사용하는 state입니다.
useState()는 두가지의 인자값을 가지는데 첫번째 인자에는 현재 상태, 두번째 인자에는 상태를 바꾸어주는 함수를 넣어줍니다.
const ColorMessage = () => {
const [color, setColor] = useState("");
const onClickColorBtn = (e) => {
setColor(e.target.value);
};
return (
<div>
<h1 id="text" style={{color}}> 컬러버튼을 클릭해보세요!</h1>
<button value="red" onClick={onClickColorBtn}>
RED
</button>
<button value="blue" onClick={onClickColorBtn}>
BLUE
</button>
<button value="green" onClick={onClickColorBtn}>
GREEN
</button>
</div>
);
};
728x90
'REACT' 카테고리의 다른 글
[React] 07. React에 styled-component 사용하기 (0) | 2020.11.13 |
---|---|
[React] 06. React Hooks 사용하기 (0) | 2020.11.11 |
[React] 04. React props 사용하기 (0) | 2020.11.08 |
[React] 03. React 컴포넌트 (0) | 2020.11.08 |
[React] 02. JSX 사용하기 (0) | 2020.11.06 |
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크