「React入門」handleClick.bind()でイベント処理をするサンプル

使用例

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Reactのサンプル</title>
<script src="/react/16.4.0/umd/react.development.js"></script>
<script src="/react-dom/16.4.0/umd/react-dom.development.js"></script>
<script src="/babel-standalone/6.26.0/babel.min.js"></script>
</head>
<body>

<div id="cft"></div>
<script type="text/babel">
class Toggle extends React.Component {
  constructor(props) {
    super(props);
    this.state = {isToggleOn: true};

  // This binding is necessary to make `this` work in the callback
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick() {
    this.setState(prevState => ({
      isToggleOn: !prevState.isToggleOn
    }));
  }

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

ReactDOM.render(
  <Toggle />,
  document.getElementById('cft')
);
</script>

</body>
</html>

 

React.js

Posted by arkgame