LoginSignup
24
10

More than 3 years have passed since last update.

Reactのstate機能

Last updated at Posted at 2020-06-19

プログラミングの勉強日記

2020年6月20日 Progate Lv.137
ReactⅠ

stateとは

 React ではユーザの動きに合わせて変わる値のことをstateという。
 今回はボタンを押すとstateが変わり表示させる文字列をを変えるプログラムを作成する。

stateの定義

 constructorの中でオブジェクトとして定義する。この定義したオブジェクトがstateの初期値となる。

constructor(props) {
    super(props);
    //オブジェクトとして定義した{count: 0}をthis.stateに代入
    this.state = {count: 0}; 
}

 このconstructor(props)super(props);の処理はいつも同じ記述なので、定型文として覚えてもよい。

stateの取得

 定義したstateはthis.stateで取得できる。

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {count: 0};
  }
  render(){
    console.log(this.state);
  ...
コンソール
{count: 0}

 コンソールにはオブジェクトが出力される。コンソールの出力で文字列はダブルクォーテーションで囲まれるが気にしなくてよい。

stateの表示

 this.stateはオブジェクトなので、this.state.プロパティ名とすることで、指定したstateのプロパティに対応する値を取得できる。

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {count: 0};
  }
  render(){
    return(
      <h1>現在ののカウントは{this.state.count}です</h1>
    );
  }
}

stateの変更

 this.setState({プロパティ:変更する値})とすると、指定されたプロパティに対応するstateの値が変更される。Reactではstateの値に直接代入することで値を変更していてはいけない。(値を変更するときはsetStateを使う)

render(){
  return(
    <h1>現在ののカウントは{this.state.count}です</h1>
    {/*ボタンがクリックされたときにcountの表示を変える*/}
    <button onClick = { ()=> {this.setState({count:2})}}>
      2
    </button>
  );
}

stateを変更するメソッド

 今回はhandleClickメソッドを作成する。

メソッドの定義
class App extends React.Component {
  handleClick(){  
    //stateのcountプロパティの値を変更する処理
  }
}
onClickイベントでメソッドを呼び出す
<button onClick={()=>{this.handleClick()}} > 
  +
</button>
メソッドを引数を渡す
class App extends React.Component {
  handleClick(count){
    this.setState({count:count);
  }
  ...
    <button onClick={()=>{this.handleClick(1)}} > 
      +
    </button>
  ...

 引数countを使ってstateのcountプロパティの値を変更する。

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

 ここまでの知識を利用して、ボタンをクリックすると数字が1ずつ増えるカウントアップ機能を作る。

App.js
import React from 'react';

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

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

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

      </div>
    );
  }
}

export default App;
24
10
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
24
10