LoginSignup
2
2

More than 3 years have passed since last update.

コンポーネント間での値の渡し方について

Last updated at Posted at 2019-05-31

classとfunctionの違い

コンポーネント間でのデータの受け渡の方法のことのようですが、
どう違うのかをわかりづらかったので覚書です:pencil2:

function


function Greeting() {
  return <p>HelloWorld</p>;
}

class


class Greeting extends React.Component {
  render() {
    return <p>HelloWorld</p>;
  }
}

出力

<Greeting />

HelloWorld
//functionでもclassでも同じ表示が出る

classの特徴

functionの方が簡単ですが、classではfunctionで使えないメソッドを使えるようです。

①Stateを使うことができる

Stateとは

 - mutable data (可変のデータ)
 - maintained by component (コンポーネントによって保持)
 - can change it (変更可)
 (Propsはただ値を渡すだけ)

②Lifecycle eventを使用できる

Lifecycle eventとは

 Componentの状態に合わせてReactが自動的に呼ぶメソッド
 ex)componentDidMount() →ComponentがDOMに追加されたときに自動的に動くメソッド

classとstateのルール

class

・ReactComponentを継承していること

class Greeting extends React.Component

・renderメソッドで値を返すこと


render() {
    return <p>HelloWorld</p>;
  }

state

・Componentとセットで使うこと
・値を更新するときはsetStateを使うこと

Stateでコンポーネントに値を渡してみる

<script type="text/babel" data-presets="env,react">
class Clock extends React.Component {

//stateで初期値を設定
    state = {time: new Date().toLocaleTimeString()};

//ComponentにMount(DOMに追加)された直後に動く
    componentDidMount() {
//1000ミリ秒(1秒)ごとにstateを更新する
      setInterval(() => {
       this.setState({ time: new Date().toLocaleTimeString() })
        }, 1000)
      }

//出力はrenderメソッド
    render() {
      return (
       <div className="time">
         The time is: {this.state.time}
       </div>
      );
    }
  }

    // Renders the App component into a div with id 'root'
    ReactDOM.render(<Clock />, document.querySelector('#root'));
</script>

<!--The App component above will be rendered into this-->
<div id="root"></div>

表示結果
スクリーンショット 2019-05-31 20.36.30.png

参照

2
2
2

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
2