onsen code monkey

個人的な日記とプログラミング備忘録です

【React】Reactの基礎知識を学習した③(イベント)

前回
hitoto28.hatenablog.com


イベント

入力したテキストをonClickイベントで反映させるサンプル

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';

//コンポーネントの作成
class SampleComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      state1 : null
    };
  }
  //テキストの設定
  setSampleText(){
      this.setState({
        state1 : this.refs.sampleText.value
      });
      this.refs.sampleText.value='';
  }
  render() {
    return (
      <div>
        <p>入力結果:{this.state.state1}</p>
        <input type="text" ref="sampleText"/>
        <input type="button" value="入力" onClick={this.setSampleText.bind(this)}/>
      </div>
    )
  }
};
 //コンポーネントの描画
ReactDOM.render(
  <SampleComponent />,
  document.getElementById('root')
);

流れとしては以下の通り

  1. コンストラクタでstate1というStateを設定
  2. JSX内のonClickイベントでsetSampleText関数を実行
  3. setSampleText関数でstate1にテキストボックスの値を設定
  4. 入力結果にstate1の値を描画

注目すべき点は、JSX内のonClickイベントで発火するthis.setMyText.bind(this)の部分。
メソッド内でコンポーネント内にアクセスするためにはbind(this)の記述が必要らしい。
ただし、JSX内でbind(this)を記述すると描画のたびに関数を生成するのでスマートではない。

省略するためにはコンストラクタ内に以下のように記述する。

constructor(props) {
  super(props);
  this.state = {
    state1 : null
  };
  this.setSampleText = this.setSampleText.bind(this);
}


↓参考サイト様
Reactのイベント設定 – React入門 - to-R Media