LoginSignup
0
0

More than 3 years have passed since last update.

Reactでカウントアップ機能を作る

Posted at

カウントアップ機能を作る

+ボタンを押すと1ずつ数字が増えていくカウントアップ機能をReactでつくる。

stateを定義する

constructor内でプロパティ名がcount、値が0stateを定義する。

constructor(props) {
    super(props);
    this.state = {count:0};
  }

ボタンとつくり、stateを表示

ボタンはbuttonのタグを使ってつくる。そして前述で定義したstatereturn内で表示させる。その際、this.state.countはJavascriptなので、{}で囲む。

render() {
    return (
      <div>
        <h1>{this.state.count}</h1>

        <button>+</button>
      </div>
    );
  }

handleClickを定義

handleClickのメソッドを定義して、statecountの値に1を足す処理を追加する。

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

buttonタグにonClickイベントを追加

buttonタグにonClickのイベントを追加して、onClickのイベント時に前述で定義したhandleClickのメソッドが呼び出されるようにする。

<button onClick={()=>{
    this.handleClick()
    }
}>+</button>

最後に

洗練さんでインターン(Progate React)です。
Progate React

GitHubのレポジトリ

最後に
現在ここでインターンしています。
まだまだ駆け出しですが頑張ります!やる気は人一倍です!
洗練

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