LoginSignup
4
2

More than 5 years have passed since last update.

Reactを始めてみた

Last updated at Posted at 2017-07-08

プロパティ | props

コンポーネント外から渡された、読込専用の値

Demo:https://codepen.io/mo4_9/pen/KqGKzX

// コンポーネントの定義
const MyComponent = React.createClass({
  // コンポーネントにrenderメソッドは必須
  render: function() {
    // コンビニエンスメソッド h1
    return React.DOM.h1(
      'null', // 属性
      `${this.props.val}` // タグ(h1)で囲う中身
    );
  }
})

// コンポーネントの利用
ReactDOM.render(
  // 定義済みコンポーネントの生成
  React.createElement(MyComponent,{val:'props'}), // コンポーネントから作成するHTML要素
  document.getElementById('main') // 出力先
)

ステート | state

コンポーネント内で保持できる、変化する値

Demo:https://codepen.io/mo4_9/pen/YQJXYd

const MyComponent = React.createClass({
  // ステートの初期化
  getInitialState: function() {
    return {count: 0} // 初期値を返す
  },
  render: function() {
    // ルート要素は一つのみなのでdivで囲う
    return React.DOM.div(
      null,
      React.DOM.input({
        type: 'text',
        onChange: this.doChange,
      }),
      React.DOM.span(null,this.state.count)
    )
  },
  doChange: function(e) {
    this.setState({count: e.target.value.length});
  }
})

ReactDOM.render(
  React.createElement(MyComponent),
  document.getElementById('main')
)

ライフサイクル

Demo:https://codepen.io/mo4_9/pen/rwqOxK

const MyComponent = React.createClass({
  componentWillMount: function() {
    // マウントされる直前
    console.log("componentWillMount");
  },
  componentDidMount: function() {
    // マウントされた直後
    // 親子関係がある場合は子からマウントされる
    console.log("componentDidMount");
  },
  componentWillUnmount: function() {
    // アンマウントされる直前
    console.log("componentWillUnmount");
  },
  componentWillReceiveProps: function(newProps) {
    // プロパティを受け取る直前
    // これからコンポーネントに渡す値(新旧の値の比較を行う)
    // 初回レンダリング(マウント)時にはcallされない
    console.log("componentWillReceiveProps",newProps);
  },
  shouldComponentUpdate: function() {
    // プロパティまたはステートを受け取る直前
    console.log("shouldComponentUpdate");
    return true; // falseで後続の処理をキャンセル
  },
  componentWillUpdate: function(nextProps,nextState) {
    // コンポーネントが更新される直前
    // ステートの更新は禁止
    // 新旧の値の比較
    console.log("componentWillUpdate",nextProps,nextState);
  },
  componentDidUpdate: function() {
    // コンポーネントが更新された直後
    // ステートの更新は禁止
    // 新旧の値の比較
    console.log("componentDidUpdate");
  },
  getInitialState: function() {
    console.log("getInitialState");
    return {count: 0}
  },
  render: function() {
    console.log("render");
    return (
      // JSXでシンプル記述
      <div>
        <input type="text" onChange={this.doChange}></input>
        <span>{this.state.count}</span>
      </div>
    )
  },
  doChange: function(e) {
    this.setState({count: e.target.value.length});
  }
})

ReactDOM.render(
  React.createElement(MyComponent,{value: 'my value'}),
  document.getElementById('main')
)

参考
React component ライフサイクル図

JSX

https://facebook.github.io/react/docs/introducing-jsx.html
https://facebook.github.io/react/docs/dom-elements.html

babel必須

  • 閉じタグが必要 ex.<br />
  • イベントハンドラはキャメルケース ex.onChange
  • 属性 class -> className, for -> htmlFor
  • スタイル属性は{{}}で囲う
  • スタイル名はキャメルケース
  • JS埋め込み{}
  • if,switchは使えない。使う場合は{}の中で。
  • ifでなく三項演算子ならそのまま使える。

Demo:https://codepen.io/mo4_9/pen/owaxYd

const MyComponent = React.createClass({
  getInitialState: function() {
    return {count: 0}
  },
  render: function() {
    return (
      <div className="hoge">
        <input type="text" onChange={this.doChange}></input>
        <span
          style={{
            fontStyle: 'italic',
            color: 'blue'
          }}
          >{this.state.count}</span>
        <p>改行の<br />テスト</p>
        <p>受け取ったprops : {this.props.val}</p>
        {
          // コンポーネント内のコメント
        }
        <p>{this.state.count >= 5 ? 'いいね!' : 'ダメだよ'}</p>
      </div>
    );
  },
  doChange: function(e) {
    this.setState({count: e.target.value.length});
  }
})

ReactDOM.render(
  <MyComponent val='hoge hoge'/>,
  document.getElementById('main')
)

ES6

Reactコンポーネントを継承するクラスをつくる

Demo:https://codepen.io/mo4_9/pen/yXRJLz

class MyComponent extends React.Component{
  render(){
    return (
      <h1>{this.props.children}</h1>
    )
  }
}

ReactDOM.render(
  <MyComponent>use ES6!</MyComponent>,
  document.getElementById('main')
)

参考
JavaScriptエンジニアが手っ取り早くReactの基礎を理解するための「超」入門書

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