React Nativeの公式ドキュメントを和訳してみる 11 -リストビューの利用

注意
  • 当記事はReact Native 0.51の公式ドキュメントの独自和訳です。間違いなどあればご指摘ください。
  • バージョン0.51のドキュメントに準拠します。
  • 参照リンク先は基本的に元サイトです。リンク先サイトを和訳したらそのページに差し替えます。
  • 本家サイトではシミュレータがあり、コードを編集しながら実行でき便利です。
  • Facebook社に無断なので怒られたら消します。

元サイト
facebook.github.io

React Nativeにはデータリストを渡すためのコンポーネントがあります。大抵はFlatListかSectionListを使う事になります。

FlatListコンポーネントは、似たような構造で変化しているデータをスクロールリストとして描画します。FlatListは時間とともに個数が変わるような長いデータリストに適しています。より包括的なScrollViewと異なり、FlatListは現在画面に表示されている要素のみを描画します。全ての要素を一度に描画するわけではありません。

FlatListコンポーネントには2つのpropが必要です。dataとrenderItemです。dataはリストの情報ソースです。renderItemはソースから一つのアイテムを取得し、描画用に整形されたコンポーネントを返します。

この例ではハードコーディングされたデータを用いた単純なFlatListを作ります。data propの中のそれぞれのアイテムはTextコンポーネントとして描画されます。FlatListBasicsコンポーネントは、それに従ってFlatListと全てのTextコンポーネントを描画します。

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

export default class FlatListBasics extends Component {
  render() {
    return (
      <View style={styles.container}>
        <FlatList
          data={[
            {key: 'Devin'},
            {key: 'Jackson'},
            {key: 'James'},
            {key: 'Joel'},
            {key: 'John'},
            {key: 'Jillian'},
            {key: 'Jimmy'},
            {key: 'Julie'},
          ]}
          renderItem={({item}) => <Text style={styles.item}>{item.key}</Text>}
        />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
   flex: 1,
   paddingTop: 22
  },
  item: {
    padding: 10,
    fontSize: 18,
    height: 44,
  },
})

// Create React Native Appを使っている時はこの行を飛ばす
AppRegistry.registerComponent('AwesomeProject', () => FlatListBasics);


もし、iOS上のUITableViewのように、セクションヘッダーなどでセクションが分割されるようなデータセットを描画したい時は、SectionListを使うのが良いでしょう。

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

export default class SectionListBasics extends Component {
  render() {
    return (
      <View style={styles.container}>
        <SectionList
          sections={[
            {title: 'D', data: ['Devin']},
            {title: 'J', data: ['Jackson', 'James', 'Jillian', 'Jimmy', 'Joel', 'John', 'Julie']},
          ]}
          renderItem={({item}) => <Text style={styles.item}>{item}</Text>}
          renderSectionHeader={({section}) => <Text style={styles.sectionHeader}>{section.title}</Text>}
          keyExtractor={(item, index) => index}
        />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
   flex: 1,
   paddingTop: 22
  },
  sectionHeader: {
    paddingTop: 2,
    paddingLeft: 10,
    paddingRight: 10,
    paddingBottom: 2,
    fontSize: 14,
    fontWeight: 'bold',
    backgroundColor: 'rgba(247,247,247,1.0)',
  },
  item: {
    padding: 10,
    fontSize: 18,
    height: 44,
  },
})

// Create React Native Appを使っている時はこの行を飛ばす
AppRegistry.registerComponent('AwesomeProject', () => SectionListBasics);

リストビューの一番よく使うケースの一つに、サーバーから取得したデータを描画するというのあるでしょう。それを実行するには、React Nativeでのネットワーキングを学ぶ必要があります。

React Nativeの公式ドキュメントを和訳してみる 10 - ScrollViewの利用

注意
  • 当記事はReact Native 0.51の公式ドキュメントの独自和訳です。間違いなどあればご指摘ください。
  • バージョン0.51のドキュメントに準拠します。
  • 参照リンク先は基本的に元サイトです。リンク先サイトを和訳したらそのページに差し替えます。
  • 本家サイトではシミュレータがあり、コードを編集しながら実行でき便利です。
  • Facebook社に無断なので怒られたら消します。

元サイト
facebook.github.io

ScrollViewは総括的なスクロールコンテナーであり、複数のコンポーネントとビューを含むことができます。スクロール可能になる要素は(リストのように)均一である必要はなく、垂直方向にも水平方向にも(horizontal プロパティを設定すれば)スクロールできます。

この例では画像と文章が混ざった垂直方向のScrollViewを作ります。

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

export default class IScrolledDownAndWhatHappenedNextShockedMe extends Component {
  render() {
      return (
        <ScrollView>
          <Text style={{fontSize:96}}>Scroll me plz</Text>
          <Image source={require('/react-native/img/favicon.png')} />
          <Image source={require('/react-native/img/favicon.png')} />
          <Image source={require('/react-native/img/favicon.png')} />
          <Image source={require('/react-native/img/favicon.png')} />
          <Image source={require('/react-native/img/favicon.png')} />
          <Text style={{fontSize:96}}>If you like</Text>
          <Image source={require('/react-native/img/favicon.png')} />
          <Image source={require('/react-native/img/favicon.png')} />
          <Image source={require('/react-native/img/favicon.png')} />
          <Image source={require('/react-native/img/favicon.png')} />
          <Image source={require('/react-native/img/favicon.png')} />
          <Text style={{fontSize:96}}>Scrolling down</Text>
          <Image source={require('/react-native/img/favicon.png')} />
          <Image source={require('/react-native/img/favicon.png')} />
          <Image source={require('/react-native/img/favicon.png')} />
          <Image source={require('/react-native/img/favicon.png')} />
          <Image source={require('/react-native/img/favicon.png')} />
          <Text style={{fontSize:96}}>What's the best</Text>
          <Image source={require('/react-native/img/favicon.png')} />
          <Image source={require('/react-native/img/favicon.png')} />
          <Image source={require('/react-native/img/favicon.png')} />
          <Image source={require('/react-native/img/favicon.png')} />
          <Image source={require('/react-native/img/favicon.png')} />
          <Text style={{fontSize:96}}>Framework around?</Text>
          <Image source={require('/react-native/img/favicon.png')} />
          <Image source={require('/react-native/img/favicon.png')} />
          <Image source={require('/react-native/img/favicon.png')} />
          <Image source={require('/react-native/img/favicon.png')} />
          <Image source={require('/react-native/img/favicon.png')} />
          <Text style={{fontSize:80}}>React Native</Text>
        </ScrollView>
    );
  }
}

// Create React Native Appを使っている時はこの行を飛ばす
AppRegistry.registerComponent(
  'AwesomeProject',
  () => IScrolledDownAndWhatHappenedNextShockedMe);

ScrollViewはpropsにpagingEnabledを設定するとスワイプしてページ単位に移動することもできます。Androidではビュー間の水平方向のスワイプはViewPagerAndroidコンポーネントを使っても可能です。

ScrollViewを一つのアイテムだけに対して使えば、その要素に対しズームが可能になります。maximamZoomScaleとminimumZoomScaleのpropを設定すればピンチを使いズームイン・アウトができるようになります。

スクロールビューは限定されたサイズの中で少量のものを配置するのに最適です。画面上に見えていない要素でも、ScrollView内の全ての要素・ビューは描画されてしまいます。もし画面サイズに合わせたもっとたくさんのアイテムの長いリストがあるならば、代わりにFlatListを使うべきです。さぁ、リストビューについて学びましょう。

React Nativeの公式ドキュメントを和訳してみる 9 - Handling Touches(タッチ動作の処理)

注意
  • 当記事はReact Native 0.51の公式ドキュメントの独自和訳です。間違いなどあればご指摘ください。
  • バージョン0.51のドキュメントに準拠します。
  • 参照リンク先は基本的に元サイトです。リンク先サイトを和訳したらそのページに差し替えます。
  • 本家サイトではシミュレータがあり、コードを編集しながら実行でき便利です。
  • Facebook社に無断なので怒られたら消します。

元サイト
facebook.github.io

ユーザーのモバイルアプリ内でのアクションは基本的にタッチです。ボタンのタップやリストのスクロール、地図のズームといったようにジェスチャーを組み合わせて使うこともできます。React Nativeで普通のジェスチャーを全て処理するためのコンポーネントを提供します。もっと発展したジェスチャーの認識もできる包括的なジェスチャー応答システムのように処理ができます。しかし、今一番知りたいコンポーネントは基本的なボタンでしょう。

基本的なボタンの表示

Buttonは基本的なボタンコンポーネントを提供します。どんなプラットフォームでもうまく描画されるでしょう。ボタンを表示する簡潔な例はこのようになります。

<Button
  onPress={() => {
    Alert.alert('You tapped the button!');
  }}
  title="Press Me"
/>

これは、iOS上では青いラベルが、そしてAndroid上では角が丸い青背景に白文字が描画されるでしょう。ボタンを押すと”onPress” 関数が呼び出されます。今回の場合はアラートのポップアップが表示されますね。必要ならば、”color” propでボタンの色を変更することもできます。

ボタン描画イメージ
引用元: http://facebook.github.io/react-native/docs/0.51/handling-touches.html

下の例を使ってボタンコンポーネントで色々試して見ましょう。表示されているプラットフォームは右下の切り替えボタンをクリックすれば選択できます。そして、”Tap to Play”をクリックしプレビューを実行しましょう。*1

import React, { Component } from 'react';
import { Alert, AppRegistry, Button, StyleSheet, View } from 'react-native';

export default class ButtonBasics extends Component {
  _onPressButton() {
    Alert.alert('You tapped the button!')
  }

  render() {
    return (
      <View style={styles.container}>
        <View style={styles.buttonContainer}>
          <Button
            onPress={this._onPressButton}
            title="Press Me"
          />
        </View>
        <View style={styles.buttonContainer}>
          <Button
            onPress={this._onPressButton}
            title="Press Me"
            color="#841584"
          />
        </View>
        <View style={styles.alternativeLayoutButtonContainer}>
          <Button
            onPress={this._onPressButton}
            title="This looks great!"
          />
          <Button
            onPress={this._onPressButton}
            title="OK!"
            color="#841584"
          />
        </View>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
   flex: 1,
   justifyContent: 'center',
  },
  buttonContainer: {
    margin: 20
  },
  alternativeLayoutButtonContainer: {
    margin: 20,
    flexDirection: 'row',
    justifyContent: 'space-between'
  }
})

// Create React Native Appを使っている時はこの行を飛ばす
AppRegistry.registerComponent('AwesomeProject', () => ButtonBasics);

Touchables (タッチ可能コンポーネントたち)

もし基本ボタンの見栄えがアプリに適さなければ、React Nativeが提供する”Touchable”なコンポーネントたちをどれでも使って独自のボタンを構築できます。”Touchableコンポーネントたちはタップジェスチャーを捕捉でき、ジェスチャーが認識された時にフィードバックを画面に表示することができます。このコンポーネントはデフォルトのスタイルはありませんが、しかし、だからこそアプリ内で見栄えよくジェスチャーを取得するのは簡単です。

どの“Touchableコンポーネントを使うかは、どんなフィードバックをユーザーに返したいかに依ります。

  • 一般的には、webでボタンやリンクを使っていたような場所ならばどこでも”TouchableHighlight”が使えます。ボタンを押すと、その背景が暗くなります。
  • Androidでは、”TouchableNativeFeedback”も検討に上がるかもしれません。インクサーフェイスリアクションリップル(さざ波アニメーション)でユーザーのタッチに反応します。
  • TouchableOpacityはフィードバックにボタンのopacityを薄くします。ボタンを押し込んだ時、ボタンの背景が透けて見えるようになります。
  • もしタップジェスチャーは処理したいけれども画面にフィードバックを表示したくない時は、TouchableWithoutFeedbackを使いましょう。


いくつかのケースでは、ユーザーがボタンを押し続けている時間を測定したいときもあるでしょう。こういった長押しは、どのTouchableコンポーネントでもonLongPress のpropを通じて処理することができます。

これら全てを動作の中で確認してみましょう。

import React, { Component } from 'react';
import { Alert, AppRegistry, Platform, StyleSheet, Text, TouchableHighlight, TouchableOpacity, TouchableNativeFeedback, TouchableWithoutFeedback, View } from 'react-native';

export default class Touchables extends Component {
  _onPressButton() {
    Alert.alert('You tapped the button!')
  }

  _onLongPressButton() {
    Alert.alert('You long-pressed the button!')
  }


  render() {
    return (
      <View style={styles.container}>
        <TouchableHighlight onPress={this._onPressButton} underlayColor="white">
          <View style={styles.button}>
            <Text style={styles.buttonText}>TouchableHighlight</Text>
          </View>
        </TouchableHighlight>
        <TouchableOpacity onPress={this._onPressButton}>
          <View style={styles.button}>
            <Text style={styles.buttonText}>TouchableOpacity</Text>
          </View>
        </TouchableOpacity>
        <TouchableNativeFeedback
            onPress={this._onPressButton}
            background={Platform.OS === 'android' ? TouchableNativeFeedback.SelectableBackground() : ''}>
          <View style={styles.button}>
            <Text style={styles.buttonText}>TouchableNativeFeedback</Text>
          </View>
        </TouchableNativeFeedback>
        <TouchableWithoutFeedback
            onPress={this._onPressButton}
            >
          <View style={styles.button}>
            <Text style={styles.buttonText}>TouchableWithoutFeedback</Text>
          </View>
        </TouchableWithoutFeedback>
        <TouchableHighlight onPress={this._onPressButton} onLongPress={this._onLongPressButton} underlayColor="white">
          <View style={styles.button}>
            <Text style={styles.buttonText}>Touchable with Long Press</Text>
          </View>
        </TouchableHighlight>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    paddingTop: 60,
    alignItems: 'center'
  },
  button: {
    marginBottom: 30,
    width: 260,
    alignItems: 'center',
    backgroundColor: '#2196F3'
  },
  buttonText: {
    padding: 20,
    color: 'white'
  }
})

// Create React Native Appを使っている時はこの行を飛ばす
AppRegistry.registerComponent('AwesomeProject', () => Touchables);

リストのスクロール、ページのスワイプ、ピンチでのズーム

モバイルアプリでよく使うジェスチャーは、他にはスワイプやパンがありますね。このジェスチャーはアイテムリストをスクロールしたり、要素のページ間をスワイプするのに使います。これら含めた他のジェスチャーを操作するために、次はスクロールビューの使い方を学びましょう。

*1:本家サイトではシミュレータがあり、コードを編集しながら実行でき便利です。

React Nativeの公式ドキュメントを和訳してみる 8 - Handling Text Input

注意
  • 当記事はReact Native 0.51の公式ドキュメントの独自和訳です。間違いなどあればご指摘ください。
  • バージョン0.51のドキュメントに準拠します。
  • 参照リンク先は基本的に元サイトです。リンク先サイトを和訳したらそのページに差し替えます。
  • 本家サイトではシミュレータがあり、コードを編集しながら実行でき便利です。
  • Facebook社に無断なので怒られたら消します。

元サイト
facebook.github.io

TextInputは基本コンポーネントの一つであり、ユーザーからのテキスト入力を可能にします。propにonChangeText を指定すれば文章が変更するたびに呼ばれる関数を設定でき、propにonSubmitEditing を指定すれば文章が投稿されたタイミングで呼ばれる関数を設定できます。

例えば、ユーザーが文字を打つ時、入力した単語を別の言語に変換させてみましょう。この新しい言語では、すべての単語はそれぞれ全く同じ🍕で記述されます。従って、”Hello there Bob”という文章は"🍕🍕🍕"に変換されます。

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

export default class PizzaTranslator extends Component {
  constructor(props) {
    super(props);
    this.state = {text: ''};
  }

  render() {
    return (
      <View style={{padding: 10}}>
        <TextInput
          style={{height: 40}}
          placeholder="Type here to translate!"
          onChangeText={(text) => this.setState({text})}
        />
        <Text style={{padding: 10, fontSize: 42}}>
          {this.state.text.split(' ').map((word) => word && '🍕').join(' ')}
        </Text>
      </View>
    );
  }
}

// Create React Native Appを使っている時はこの行を飛ばす
AppRegistry.registerComponent('AwesomeProject', () => PizzaTranslator);

この例の中ではtextをstateに保存していますが、これは時間とともに変わっていく値だからです。

文章入力に関してやりたいことはもっとたくさんあるでしょう。入力中の文章内のバリデーションなどですね。より詳細な例はReactのドキュメント内の"コントロールされたコンポーネント"の項、またはTextInputのレファレンスを参照してください。

文章の入力はユーザーをアプリの間でやり取りする一つの方法です。次は、他のインプット方法を見てタッチ動作の処理方法を学びましょう。

React Nativeの公式ドキュメントを和訳してみる 7 - Layout with Flexbox(フレックスボックスを用いたレイアウト)

注意
  • 当記事はReact Native 0.51の公式ドキュメントの独自和訳です。間違いなどあればご指摘ください。
  • バージョン0.51のドキュメントに準拠します。
  • 参照リンク先は基本的に元サイトです。リンク先サイトを和訳したらそのページに差し替えます。
  • 本家サイトではシミュレータがあり、コードを編集しながら実行でき便利です。
  • Facebook社に無断なので怒られたら消します。

元サイト
facebook.github.io

コンポーネントにはflexboxのアルゴリズムを使って子要素のレイアウトを指定できます。flexboxは画面サイズが変わっても同じレイアウトを提供できるよう設計されています。

通常はflexDirection, alignItems, justifyContentを組み合わせて正しいレイアウトへと近づけていきます。

flexboxはReactNative内でもweb上のCSSと同じように働きますが、少しだけ例外があります。初期値がいくつか異なり、flexDirectionの初期値はrow(横方向)ではなくcolumn(縦方向)に、そしてflexに設定するパラメータは数字ひとつのみをサポートしています。

Flex Direction (フレックスの方向)

flexDirectionをコンポーネントのstyleに追加すると、レイアウト内で主軸が決定されます。子要素を水平(row)に、または垂直(column)に並べる必要がありますか?何も指定しないとcolumnになります。

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

export default class FlexDirectionBasics extends Component {
  render() {
    return (
      // Try setting `flexDirection` to `column`.
      <View style={{flex: 1, flexDirection: 'row'}}>
        <View style={{width: 50, height: 50, backgroundColor: 'powderblue'}} />
        <View style={{width: 50, height: 50, backgroundColor: 'skyblue'}} />
        <View style={{width: 50, height: 50, backgroundColor: 'steelblue'}} />
      </View>
    );
  }
};

// Create React Native Appを使っている時はこの行を飛ばす
AppRegistry.registerComponent('AwesomeProject', () => FlexDirectionBasics);
Justify Content ( 要素の整列 )

コンポーネントのstyleにjustifyContentを追加すると、主軸に沿った方向への子要素の配置方法を決定できます。子要素を始端、中央、終端、または等間隔に間を空けて配置しますか?利用可能なオプションはflex-start, center, flex-end, space-around, そしてspace-betweenです。

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

export default class JustifyContentBasics extends Component {
  render() {
    return (
      // Try setting `justifyContent` to `center`.
      // Try setting `flexDirection` to `row`.
      <View style={{
        flex: 1,
        flexDirection: 'column',
        justifyContent: 'space-between',
      }}>
        <View style={{width: 50, height: 50, backgroundColor: 'powderblue'}} />
        <View style={{width: 50, height: 50, backgroundColor: 'skyblue'}} />
        <View style={{width: 50, height: 50, backgroundColor: 'steelblue'}} />
      </View>
    );
  }
};

// Create React Native Appを使っている時はこの行を飛ばす
AppRegistry.registerComponent('AwesomeProject', () => JustifyContentBasics);
Align Items 要素の整列

コンポーネントのstyleにalignItemsを追加すると、第二軸(主軸がrowならば第二軸はcolumnとなり、逆も同様)に沿った子要素の並びを決定できます。子要素を始端、中央、終端、または全体に引き伸ばして並べる必要がありますか?利用可能なオプションはflex-start, center, flex-end, そしてstretchです。

stretchを有効にするには、子要素は第二軸に沿った方向に固定次元を持っていてはいけません。下の例で言えば、alignments: stretchを設定しても子要素からwidth: 50 を外さなければ何も起こりません。

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

export default class AlignItemsBasics extends Component {
  render() {
    return (
      // Try setting `alignItems` to 'flex-start'
      // Try setting `justifyContent` to `flex-end`.
      // Try setting `flexDirection` to `row`.
      <View style={{
        flex: 1,
        flexDirection: 'column',
        justifyContent: 'center',
        alignItems: 'center',
      }}>
        <View style={{width: 50, height: 50, backgroundColor: 'powderblue'}} />
        <View style={{width: 50, height: 50, backgroundColor: 'skyblue'}} />
        <View style={{width: 50, height: 50, backgroundColor: 'steelblue'}} />
      </View>
    );
  }
};

// Create React Native Appを使っている時はこの行を飛ばす
AppRegistry.registerComponent('AwesomeProject', () => AlignItemsBasics);
さらに深みへ

ここまで基本をカバーしてきました。しかし、レイアウトに必要になるであろうstyleは他にもたくさんあります。レイアウトを調整するすべてのpropsのリストはこちらのドキュメントにまとまっています。

実際のアプリ構築ができるようになるところまで近づいてきました。一つ、まだ見逃していることがありますね。ユーザーからの入力を取得する方法です。さあ、TextInputコンポーネントを使い文章入力をコントロールする方法を学びましょう。

React Nativeの公式ドキュメントを和訳してみる 6 - Height and Width

注意
  • 当記事はReact Native 0.51の公式ドキュメントの独自和訳です。間違いなどあればご指摘ください。
  • バージョン0.51のドキュメントに準拠します。
  • 参照リンク先は基本的に元サイトです。リンク先サイトを和訳したらそのページに差し替えます。
  • 本家サイトではシミュレータがあり、コードを編集しながら実行でき便利です。
  • Facebook社に無断なので怒られたら消します。

元サイト
facebook.github.io

コンポーネントの高さと幅によってスクリーン上で描画される大きさが決まります。

固定次元 (Fixed Dimensions)

コンポーネントの次元を設定する一番単純な方法は、styleに固定値でwidthとheightを追加する事です。React Nativeのすべての次元は単位がなく、独立した階層のピクセルで表されます。

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

export default class FixedDimensionsBasics extends Component {
  render() {
    return (
      <View>
        <View style={{width: 50, height: 50, backgroundColor: 'powderblue'}} />
        <View style={{width: 100, height: 100, backgroundColor: 'skyblue'}} />
        <View style={{width: 150, height: 150, backgroundColor: 'steelblue'}} />
      </View>
    );
  }
}

// Create React Native App使ってたらこの行はとばす
AppRegistry.registerComponent('AwesomeProject', () => FixedDimensionsBasics);

この方法での次元の設定は、普通スクリーンサイズに関わらずコンポーネントを常に正確に同じサイズで描画する際に使われます。

フレックス次元 (Flex Dimensions)

コンポーネントのstyleでflexを使うと、描画可能なスペースを基準にコンポーネントが動的に拡大・縮小します。通常はflex: 1を使います。これは、コンポーネントを描画域全体に広げます。同じ親コンポーネントを持つコンポーネントが複数ある場合、それぞれのコンポーネントは等幅で分割されます。flexの値が大きくなるほど、兄弟要素と比較してコンポーネントの占める場所の割合は大きくなります。

コンポーネントのサイズが0でなければ、コンポーネントは描画域全体に広がります。もし親コンポーネントに固定値のwidth,heightやflexが設定されていない場合、親コンポーネントは0次元となりflexがついた子要素は表示されません。

export default class FlexDimensionsBasics extends Component {
  render() {
    return (
      // 親Viewから`flex: 1` を外すとどうなるでしょう?
      // 親要素は次元を持たなくなるため、子要素は広がることができません。
      //  `flex: 1`の代わりに`height: 300`を追加するとどうなるでしょうか?
      <View style={{flex: 1}}>
        <View style={{flex: 1, backgroundColor: 'powderblue'}} />
        <View style={{flex: 2, backgroundColor: 'skyblue'}} />
        <View style={{flex: 3, backgroundColor: 'steelblue'}} />
      </View>
    );
  }
}

// Create React Native App使ってたらこの行は飛ばす
AppRegistry.registerComponent('AwesomeProject', () => FlexDimensionsBasics);

コンポーネントのサイズを調整できるようになったら、次のステップはスクリーン上でどのようにレイアウトするかを学びましょう。

React Nativeの公式ドキュメントを和訳してみる 5 - Style

注意
  • 当記事はReact Native 0.51の公式ドキュメントの独自和訳です。間違いなどあればご指摘ください。
  • バージョン0.51のドキュメントに準拠します。
  • 参照リンク先は基本的に元サイトです。リンク先サイトを和訳したらそのページに差し替えます。
  • 本家サイトではシミュレータがあり、コードを編集しながら実行でき便利です。
  • Facebook社に無断なので怒られたら消します。

元サイト
facebook.github.io

ReactNativeでは、styleを定義するのに特別な言語も記法も用いません。JavaScriptを使うだけです。全てのコアコンポーネントでstyleというpropが使用できます。styleの名前と値はweb上のCSSと大体同じですが、名前がキャメルケースになります。例えば、background-colorはbackgroundColorになります。

styleというpropは単純な昔からあるJavaScriptのオブジェクトで表されます。もっとも単純で、普段から例としてあげるコードです。複数のstyleを配列で渡すこともできます。後に書かれたstyleが優先されるため、styleを継承させるためにも使えるでしょう。

コンポーネントが複雑に肥大してくると、StyleSheet.createを使って複数のstyleを一箇所に定義した方が綺麗になることがしばしばあります。これは、その例です。

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

export default class LotsOfStyles extends Component {
  render() {
    return (
      <View>
        <Text style={styles.red}>just red</Text>
        <Text style={styles.bigblue}>just bigblue</Text>
        <Text style={[styles.bigblue, styles.red]}>bigblue, then red</Text>
        <Text style={[styles.red, styles.bigblue]}>red, then bigblue</Text>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  bigblue: {
    color: 'blue',
    fontWeight: 'bold',
    fontSize: 30,
  },
  red: {
    color: 'red',
  },
});

// Create React Native App使ってたらこの行は飛ばす
AppRegistry.registerComponent('AwesomeProject', () => LotsOfStyles);

一つのコモンパターンとして、styleのpropを受け付けるコンポーネントを作成し、サブコンポーネントをデザインするために順番につかう方法があります。CSSでいう”cascade”を作るのに使えますね。

テキストのスタイルをカスタマイズするのにはたくさんのやり方があります。完全な一覧はテキストコンポーネントのレファレンスをチェックしてください。

さて、テキストを美しく彩ることができるようになりました。次のステップは、スタイルマスターになるためにコンポーネントのサイズをコントロールする術を学びましょう。