LoginSignup
8
7

More than 5 years have passed since last update.

ReactNative入門④ ~Stateに触れる~

Last updated at Posted at 2017-11-26

State

propsの他にもコンポーネントのデータを管理するものがあり、stateといいます。
propsとstateの違いは、簡単にまとめると以下のようになります。詳しくはReactのstateの公式ドキュメントや記事を読むと良いでしょう。

props state
設定元 親コンポーネント 自身
変更 しない する

stateはconstructorで初期化し、stateの値を変更したいときは、setStateで変更します。

コードを確認する

では、今回のソースコードを確認しましょう。

import React, { Component } from 'react';
import { AppRegistry, Text, View } from 'react-native';


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

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

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

export default class BlinkApp extends Component {
  render() {
    return (
      <View>
        <Blink text='I love to blink' />
        <Blink text='Yes blinking is so great' />
        <Blink text='Why did they ever take this out of HTML' />
        <Blink text='Look at me look at me look at me' />
      </View>
    );
  }
}

AppRegistry.registerComponent('AwesomeProject', () => BlinkApp);

解説

StateとPropsの使い分けに注目です。
画面に表示するテキストは、変わらないので親コンポーネントであるBlinkAppがBlinkコンポーネントにpropsとして定義しています。
反対に、テキストの表示・非表示は交互に 変化 していくのでstateのshowTextとして定義します。
そして、showTextをsetIntervalを使って1秒毎にtrue, falseを切り替え、テキストの表示・非表示を切り替えています。
すると、このようにテキストが表示・非表示されるようになります。

b33b42846a01723084ec5a7026c61d6a.gif

8
7
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
8
7