LoginSignup
5
3

More than 5 years have passed since last update.

React.jsでボタン作り

Last updated at Posted at 2016-06-03

React.js: Getting Startedを参考
クリックすると数字が増えるボタンを作る

Plunkerを使用。

index.html
<!DOCTYPE html>
<html>
  <head>    
  </head>

  <body>
    <div id="root"></div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.34/browser.min.js"></script>
    <script src="https://fb.me/react-0.13.3.js"></script>
    <script src="script.js" type="text/babel"></script>
  </body>
</html>
script.jsx
var Button = React.createClass({
  localHandleClick: function(){
    this.props.localHandleClick(this.props.increment);
  },
  render: function(){
    return (
      <button onClick={this.localHandleClick}>+{this.props.increment}</button>
    );
  }
});

var Result = React.createClass({
  render: function(){
    return(
      <div>{this.props.localCounter}</div>
    );
  }
});

var Main = React.createClass({
  getInitialState: function(){
    return {counter: 0};
  },
  handleClick: function(increment){
    this.setState({counter:this.state.counter+increment});
  },
  render: function(){
    return(
      <div>
        <Button localHandleClick={this.handleClick} increment={1} />
        <Button localHandleClick={this.handleClick} increment={5} />
        <Button localHandleClick={this.handleClick} increment={10} />
        <Button localHandleClick={this.handleClick} increment={100} />
        <Result localCounter={this.state.counter} />
      </div>
    );
  }
});

React.render(<Main />, document.getElementById("root"));

とりあえずReact.createClassしてrender書く

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