LoginSignup
1
0

More than 3 years have passed since last update.

【React】カウントアップ機能を実装してみた

Last updated at Posted at 2020-07-19

今回はReactを利用して下図のようなカウントアップ機能を実装していきます。
React初学者の方は、このような簡単な実装でコツを掴んでいくと良いと思います。

完成図

Image from Gyazo

0.雛形

完成コードです。
要所で詳細に説明していきます。

App.js
import React from 'react';

class App extends React.Component {
  constructor(props) {
    super(props)
    this.state = {count: 0};
  }

  hendleClick() {
    setState({count: this.state.count + 1});
  }

  render() {
    return(
      <div>
        <p>{this.state.count}</p>
        <button onClick={()=>{this.handleClick()}}>+</button>
      </div>
    );
  }
}

1.stateを定義

stateを使って初期値の設定をしていきます。

App.js
import React from 'react';

class App extends React.Component {
  constructor(props) {
    super(props)
    // this.stateでcountプロパティの初期値を0に設定します
    this.state = {count: 0};
  }
}

2.メソッドを定義

setStateを使って、countの値を変更するhandleClickメソッドを作ります。

App.js
import React from 'react';

class App extends React.Component {
  constructor(props) {
    super(props)
    this.state = {count: 0};
  }

  hendleClick() {
    // 「this.state.count + 1」 とすることでstateのcountの値に1を足すメソッドを定義する
    setState({count: this.state.count + 1});
  }
}

3.イベントの呼び出し

クリックイベントでhandleClickメソッドを呼び出し、ボタンをクリックする度にカウントの表示を変更してみましょう。

App.js
import React from 'react';

class App extends React.Component {
  constructor(props) {
    super(props)
    this.state = {count: 0};
  }

  hendleClick() {
    this.setState({count: this.state.count + 1});
  }

  render() {
    return(
      <div>
        // stateを表示
        <p>{this.state.count}</p>
        // クリックイベントでhandleClickメソッドを呼び出す
        <button onClick={()=>{this.handleClick()}}>+</button>
      </div>
    );
  }
}

補足(setStateについて)

setStateが実行されるタイミングはReactが勝手に決めるので、
下図のように書いてしまうと、count の値がほかの処理で書き換わってしまって、うまくカウントアップできない場合もあります。

App.js
  hendleClick() {
    this.setState({count: this.state.count + 1});
  }

そこで setState では state の変更前の値を取得できるようになっていて、
その場合は prevState で…、アロー関数式で下図ように書いてあげれば、 prevState に直前の値が入ってくるので、その値を使って書き換えてあげれば OK です。

App.js
  hendleClick() {
    this.setState(prevState => {
      return(
        //  count というキーの値を prevState.count + 1 としてあげればカウントされます
        count: prevState + 1
      );
    });
  }

以上

1
0
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
1
0