LoginSignup
2
5

More than 3 years have passed since last update.

【JavaScript修行】React:イベント処理について

Posted at

https://ja.reactjs.org/docs/handling-events.html
今日は上記のドキュメントの読み解き作業の覚書になります。

Reactのイベント処理って?

→DOM要素のイベント処理とそっくり!
ただ異なる文法もある。

<button onclick="event()">
 イベントボタン
</button>

Reactだとこのようになる。

<button onclick={event}>
 イベントボタン
</button>
  • イベント名をキャメルケースでかく
  • イベントハンドラは文字列ではなく関数を渡す

上記2点がJSXとHTMLで異なっている。

preventDefault()したい時

function ActionLink() {
  function handleClick(e) {
    e.preventDefault();
    console.log('The link was clicked.');
  }
  return (
    <a href="#" onClick={handleClick}>
      Click me
    </a>
  );
}

ReactDOM.render(
 <ActionLink />,
  document.querySelector('body')
)

ReactではDOM生成後ではなく、
最初にレンダリングされる際にaddEventListenerを呼び出す。

上記はファンクションのコンポーネントでのイベントハンドラ。
クラスでのイベントハンドラはクラスのメソッドになる。
以下の通り。

class Toggle extends React.Component {
  constructor(props) {
    super(props);
    this.state = {isToggleOn: true};

    this.handleClick = this.handleClick.bind(this); //注目
  }

  handleClick() {
    this.setState(state => ({
      isToggleOn: !state.isToggleOn //stateをトグル
    }));
  }

  render() {
    return (
      <button onClick={this.handleClick}>
        {this.state.isToggleOn ? 'ON' : 'OFF'}
      </button>
    );
  }
}

ReactDOM.render(
  <Toggle />,
  document.querySelector('root')
);

thisに注意します。
render部分で書かれているthis.handleClickthisは関数外なのでバインドされていません。
なのでbindしておく必要があります。
→ bindの学習記録。

render()で書き出しているボタンには、onclickのイベントハンドラがあり、this.handleClickによってstateがトグルされ、それを感知し再描画されます。
その際インナーテキストがトグルの変数によって変わります。

bindが面倒な場合、回避法が2つある。
①パブリッククラスフィールド構文を使う(なんだそれ)
※Stage 3 Proposalらしい。

class LoggingButton extends React.Component {
  // 注意: これは実験的な構文になります。
  handleClick = () => {
    console.log('this is:', this);
  }

  render() {
    return (
      <button onClick={this.handleClick}>
        Click me
      </button>
    );
  }
}

なんだか不思議な構文です。()を無理やりつけたという感じです。詳細求む。
Create React Appではデフォルトで使える構文のようです。

②アロー関数の使用


class LoggingButton extends React.Component {
  handleClick() {
    console.log('this is:', this);
  }

  render() {
    return (
      <button onClick={(e) => this.handleClick(e)}>
        Click me
      </button>
    );
  }
}

thisには上記の対策をとって倒しましょう!

2
5
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
2
5