## Lottery Component
- Props
- title
- numOfBalls
- maxNum
- State
- nums: array of [num, num, num, ...] for balls
- Events
- onClick: regenerate nums in state
## LotteryBall Component
- Props
- num
- No State, No Events!
Lottery component.js
import React, { Component } from 'react';
import Ball from './Ball';
import './Lottery.css';
class Lottery extends Component {
static defaultProps = {
title: 'Lotto',
numOfBalls: 6,
maxNum: 40
};
constructor(props) {
super(props);
this.state = { nums: Array.from({ length: this.props.numOfBalls }) }; // numOfBalls의 값만큼의 길이를 가진 nums 배열생성
this.handleClick = this.handleClick.bind(this);
}
generate() {
//현재 nums배열 복사해서 새배열 생성 ->랜덤을 통해 숫자 넣어줌
this.setState(curState => ({
nums: curState.nums.map(
num => Math.floor(Math.random() * this.props.maxNum) + 1
)
}));
}
handleClick() {
this.generate();
}
render() {
// nums 배열을 복사해서 그 배열의 길이, 값을 가진 Ball 생성 // Ball num = undefined
return (
<section className="Lottery">
<h1>{this.props.title}</h1>
<div>
{this.state.nums.map(nums => <Ball num={nums} />)}
</div>
<button onClick={this.handleClick}>Generate Number</button>
</section>
);
}
}
export default Lottery;
css
.Lottery {
padding: 2em;
margin: 2em;
border: 2px solid salmon;
border-radius: 10px;
color: grey;
}
.Lottery button{
margin: 2em;
padding: 1em;
color: antiquewhite;
background-color: tomato;
border-style: none;
border-radius: 10px;
}
Ball component.js
import React, { Component } from 'react';
import './Ball.css';
class Ball extends Component {
// no need constructor, this is component that does not have state.
render() {
return (
<div className="Ball">
{this.props.num}
</div>
);
}
}
export default Ball;
css
.Ball {
background-color: tomato;
border-radius: 50%;
color: antiquewhite;
display: inline-block;
width: 3em;
height: 2.25em;
padding-top: 0.75em;
text-align: center;
margin-right: 0.5em;
font-weight: bold;
font-size: 1.5em;
}
'react' 카테고리의 다른 글
React events : event method binding and passing method to child (0) | 2020.06.14 |
---|---|
State exercise : coin flipper (0) | 2020.06.14 |
More State : data structure and designing state (0) | 2020.06.14 |
More State : setting state using state (0) | 2020.06.13 |
State clicker exercise : who is lucky (0) | 2020.06.13 |