LoginSignup
5
4

More than 5 years have passed since last update.

React 簡単なSample集

Last updated at Posted at 2017-07-23

Reactハンズオンに参加したのでその備忘録を残したいと思います。

React初期設定

・インストール

command
$ npm install -g create-react-app

・作業場で環境構築

command
$ create-react-app myapp
$ cd myapp
$ npm start

・ルートポイント

src/index.js
ReactDOM.render(
  <App />,
  document.getElementById('root')
);

文字をチカチカさせる

・setInterval関数を使って文字をチカチカさせる書き方

src/App.js
import React, { Component } from 'react';
import Text from './Text';

class App extends Component {
  render() {
    return (
      <div>
        <Text text='チカチカ文字' />
      </div>
    )
  }
}

export default App;
src/Text.js
import React, { Component } from 'react';

class Text extends Component {
  constructor(props) {
    super(props);
    this.state = {
      showText: true,
    };

    setInterval(() => {
      this.setState({
        showText: !this.state.showText,
      });
    }, 1000);
  }

  render() {
    const text = this.state.showText? this.props.text : '';
    return (
      <div>
        {text}
      </div>
    )
  }
}

export default Text;

クリックカウント

src/App.js
import React, { Component } from 'react';
import Button from './Button';

class App extends Component {
  render() {
    return (
      <div>
        <Button />
      </div>
    )
  }
}

export default App;
src/Button.js
import React, { Component } from 'react';

class Button extends Component {
  constructor(props) {
    super(props);

    this.state = {
      count: 0,
    }
    this._addCount = this._addCount.bind(this); // イベントハンドラでthisをbindさせるため
  }

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

  render() {
    return (
      <div>
        <button onClick={this._addCount}>
          button
        </button>
        <p>{this.state.count}</p>
      </div>
    )
  }
}

 export default Button;

その他のbindの書き方

・onClickに書く

src/Button.js
<button onClick={this._addCount.bind(this)}>

・arrow functionで書く(bind不要)

src/Button.js
_addCount = () => {
  this.setState({
    count: this.state.count + 1,
  });
}

参考サイト

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