LoginSignup
6
4

More than 5 years have passed since last update.

React Nativeで画面UIを作る時に横に並べる方法(Androidエンジニア目線)

Posted at

背景

私はAndroidエンジニアですが、iOS向けアプリも作りたいなぁと思い、React Nativeに手を出しました。

実装

React Nativeでは、以下のように render(){} でViewを返します。
このViewがAndroidのXMLのようなものです。(という解釈をしました)

App.tsx
export default class App extends Component<Props> {
  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.welcome}>Welcome to React Native!</Text>
        <Text style={styles.instructions}>To get started, edit App.js</Text>
        <Text style={styles.instructions}>{instructions}</Text>
      </View>
    );
  }
}

画面はこうです。
スクリーンショット 2019-04-24 10.06.09.png

あーなるほど。 View ってのは、Androidでいう LinearLayout なのですね!(という解釈をしました)
そしてレイアウトはCSSみたいにこんな感じで定義します。

App.tsx
const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  instructions: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
});

Textとかを横に並べる方法

View は、何も設定しないと LinearLayoutandroid:orientation:vertical が着いている状態っぽくなります。
android:orientation: horizontal にしたい場合は、 FlexBox を使います。
以下のようにします。

App.tsx
const styles = StyleSheet.create({
  container: {
    flex: 1,
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  }

flexDirection: 'row',

これを追加しました。これにより、 horizontal になります。
画面はこのように変わります。
スクリーンショット 2019-04-24 10.40.53.png

縦に並んでいたものが、横に並ぶようになりました!

まとめ

AndroidネイティブでやっていたことをReact Nativeで実現するにはどうしたらいいんだろう…という悩みはありますが、
少しずつ理解していきます!

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