LoginSignup
0
1

More than 5 years have passed since last update.

ReactでFizzBuzz

Last updated at Posted at 2019-03-26

こんにちは。
無性にFizzBuzzしたくなる時ってありますよね?(僕はあります)
今回は、Reactで良く見かけるカウントアップのサンプルを弄って作っていきます。

準備

  • create-react-appでポチポチやっていきます。
npm i create-react-app -g
create-react-app ts-react-fizzbuzz --typescript

実装

  • 以下のファイルを書き換えます。
src\App.tsx
import React, { Component } from 'react';
import './App.css';

interface IProps {}
interface IState {
  count: number;
  fizzBuzz: string;
}

class App extends Component<IProps, IState> {
  constructor(props: IProps) {
    super(props);
    this.state = {
      count: 1,
      fizzBuzz: this.toFizzBuzz(1)
    };
    this.countUp = this.countUp.bind(this);
    this.countDown = this.countDown.bind(this);
  }

  toFizzBuzz(value: number): string {
    if (value <= 0) {
      return '';
    }
    const fizzBuzz: string =
      `${value % 3 === 0 ? 'Fizz' : ''}${value % 5 === 0 ? 'Buzz' : ''}` ||
      value.toString();
    return fizzBuzz;
  }

  countUp() {
    const value = this.state.count + 1;
    this.setState({
      count: value,
      fizzBuzz: this.toFizzBuzz(value)
    });
  }

  countDown() {
    const value = this.state.count === 1 ? 1 : this.state.count - 1;
    this.setState({
      count: value,
      fizzBuzz: this.toFizzBuzz(value)
    });
  }

  render() {
    return (
      <div>
        <div className="count">{this.state.fizzBuzz}</div>
        <input type="button" value="+" onClick={this.countUp} />
        <input type="button" value="-" onClick={this.countDown} />
      </div>
    );
  }
}

export default App;
src\App.css
#root {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  text-align: center;
}

.count {
  margin-bottom: 10px;
  font-size: 200px;
}

input[type='button'] {
  margin: 10px;
  width: 50px;
  font-size: 50px;
}

実行

npm run start

結果確認

GIF

良いですね。

ソースコード

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1