티스토리 뷰
1. 구구단 게임 소개
2. 구구단 게임 구현
1. 구구단 게임 소개

위의 그림처럼 <input> 태그 안에 숫자를 입력하고 submit 버튼을 클릭하면 해당 숫자에 대한 구구단이 출력되도록 React로 구현해보고자 한다.
2. 구구단 게임 구현
import React, {Component} from 'react';
import GuguForm from './GuguForm';
import GuguList from './GuguList';
class GuguClass extends Component{
state = {
value:null
};
handleSubmit = e => {
e.preventDefault();
this.setState({
...this.state,
value:parseInt(e.target.gugu.value)
});
};
render() {
return(
<>
<GuguForm onSubmit={this.handleSubmit}/>
<GuguList value={this.state.value}/>
</>
)
}
};
위의 코드는 GuguClass.jsx 파일의 내용이다.
GuguClass라는 컴포넌트 안에 GuguForm과 GuguList라는 컴포넌트가 포함되어 있다.
GuguClass의 초기 state의 value 값은 null이다. GuguForm에서 submit을 했을 때 handleSubmit 함수가 실행되는데, handleSubmit 함수 안에는 setState 메소드가 있어서 state가 계속 바뀌게 된다. GuguList 컴포넌트의 value값도 this.state.value이므로 같이 바뀌게 된다.
import React, {Component} from 'react';
class GuguForm extends Component{
render() {
return(
<>
<h2>구구단을 외자!</h2>
<form onSubmit={this.props.onSubmit}>
<input type="number" name="gugu" placeholder='숫자를 입력하세요.'/>
<input type="submit" value="submit"/>
</form>
</>
)
}
}
export default GuguForm;
위의 코드는 GuguForm.jsx 파일의 내용이다.
GuguForm 컴포넌트에는 <form> 태그가 있는데, 첫 번째 <input> 태그는 type이 number로 숫자만 입력이 가능하다. 두 번째 <input> 태그의 type은 submit이다.
import React, {Component} from 'react';
class GuguList extends Component{
list = (n) => {
const arr = Array(9).fill(null);
const result = arr.map((v, k) => {
return <li key={k}>{n} * {k+1} = {n*(k+1)}</li>
});
return (
<ul>
<li>{n}단입니다.</li>
{result}
</ul>
)
};
render() {
return(
<>
{this.props.value === null ? '몇 단을 출력할까?' : this.list(this.props.value)}
</>
)
}
}
export default GuguList;
위의 코드는 GuguList.jsx 파일의 내용이다.
GuguList 컴포넌트는 this.props.value가 null일 때에는 '몇 단을 출력할까?' 라는 내용만 나오고, null이 아닐 때 (숫자를 입력했을 때) list 함수를 실행한다.
this.list() 안의 this.props.value는 입력한 숫자이다. list 함수는 길이가 9이고, 모든 원소의 값이 null인 arr 배열을 <li> 태그에 mapping 하여 입력한 숫자에 해당하는 구구단을 뽑아낸다.
'React' 카테고리의 다른 글
[React] 페이지를 누가 렌더 하는가? (CSR vs. SSR) (0) | 2022.04.21 |
---|---|
[React] css 적용하기 (0) | 2022.04.20 |
webpack 소개 및 사용 방법 (0) | 2022.04.20 |
[React] 틱택토 게임 구현 (0) | 2022.04.17 |
[React] props & state (0) | 2022.04.13 |
- Total
- Today
- Yesterday
- bom
- 변수
- keyword
- Document Object Model
- Navigator 객체
- 컴파일
- Screen 객체
- 리액트 #React #props #state #javascript
- Char
- Browser Object Model
- int
- History 객체
- c언어
- 키워드
- DOM
- short
- location 객체
- stdio.h
- 자료형
- window 객체
- gcc
- long
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |