🦊 Class형
- state 초기화: state 오브젝트에 모든 변수를 한번에 초기화
state = {
kiddo : '우리집 강아지',
}
- state 변경: this.setState이용
this.setState((prevState) => {
return {
kiddo: '안녕',
}
};
- render안에서 불러올 때: this.state로 불러오기
{this.state.kiddo}
🦊 함수형
const [kiddo, setKiddo] = React.useState('우리집 강아지');
setKiddo('안녕');
{kiddo}
- 아래는 제로초님 리액트 웹게임 강의에서 나왔던 클래스형, 함수형 코드입니다.
class GuGuDan extends React.Component {
state = {
first: Math.ceil(Math.random() * 9),
second: Math.ceil(Math.random() * 9),
value: '',
result: '',
};
onSubmit = (e) => {
e.preventDefault();
if (parseInt(this.state.value) === this.state.first * this.state.second) {
this.setState((prevState) => {
return {
result: '정답: ' + prevState.value,
first: Math.ceil(Math.random() * 9),
second: Math.ceil(Math.random() * 9),
value: '',
};
});
this.input.focus();
} else {
this.setState({
result: '땡',
value: '',
});
this.input.focus();
}
};
onChange = (e) => {
this.setState({ value: e.target.value });
};
input;
onRefInput = (c) => { this.input = c; };
render() {
return (
<React.Fragment>
<div>{this.state.first} 곱하기 {this.state.second}는?</div>
<form onSubmit={this.onSubmit}>
<input ref={this.onRefInput} type="number" value={this.state.value} onChange={this.onChange}/>
<button>입력!</button>
</form>
<div>{this.state.result}</div>
</React.Fragment>
);
}
}
const GuGuDan = () => {
const [first, setFirst] = React.useState(Math.ceil(Math.random() * 9));
const [second, setSecond] = React.useState(Math.ceil(Math.random() * 9));
const [value, setValue] = React.useState('');
const [result, setResult] = React.useState('');
const inputEl = React.useRef(null);
const onSubmitForm = (e) => {
e.preventDefault();
if (parseInt(value) === first * second) {
setResult('정답');
setFirst(Math.ceil(Math.random() * 9));
setSecond(Math.ceil(Math.random() * 9));
setValue('');
inputEl.current.focus();
} else {
setResult('땡');
setValue('');
inputEl.current.focus();
}
};
return (
<React.Fragment>
<div>{first} 곱하기 {second}는?</div>
<form onSubmit={onSubmitForm}>
<input
ref={inputEl}
type="number"
value={value}
onChange={(e) => setValue(e.target.value)}
/>
<button>입력!</button>
</form>
<div id="result">{result}</div>
</React.Fragment>
);
};