HOWTO · React Native

React Native で要素を揃える

このチュートリアルでは、React Native で要素を配置する方法について説明します。

この記事では、必要な例と説明を使用して、React-Native 要素を調整し、理解しやすくする方法を説明します。

React Native で要素を揃える

項目の整列には、水平方向と垂直方向の 2 種類の配置が利用できます。 水平方向の配置には、上、中央、およびボタンの 3つのプロパティがあり、垂直方向の配置には、左、中央、および右の 3つのプロパティがあります。

flex を使用すると、以下の構文を使用してアイテムを簡単に整列できます。

構文:

container: {flex: 1
       justifyContent: 'center', // For aligning vertically
       alignItems: 'center', // For aligning horizontally
    }

flex を使用して React-Native 要素を配置する

// Importing necessary packages
import {StatusBar} from 'expo-status-bar';
import {Image, StyleSheet, Text, View, ViewComponent, ViewPagerAndroidBase} from 'react-native';

// Our main function
export default function App() {
  let img = './assets/image1.jpg';  // Declaring a variable that hold the image
                                    // location
  return (
      <View style = {styles.container}><Text>This is a body aligned center<
          /Text>
      <View style={styles.container01}>
        <Text>I am Left</Text>
      <Image style = {styles.img} source =
       {
         require(img)
       } />
        <StatusBar style="auto" />
      </View>
    <View style={styles.container02}>
        <Text>I am Center</Text>
      <Image style = {styles.img} source =
       {
         require(img)
       } />
        <StatusBar style="auto" />
      </View>
    <View style={styles.container03}>
        <Text>I am Right</Text>
      <Image style = {styles.img} source = {
        require(img)
      } />
        <StatusBar style="auto" /></View>
    </View>);
}

const styles = StyleSheet.create({
  // Providing some styles to the UI
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
    margin: 50,
  },
  container01: {
    flex: 1,
    alignSelf: 'flex-start',
  },
  container02: {
    flex: 1,
    alignSelf: 'center',
  },
  container03: {
    flex: 1,
    alignSelf: 'flex-end',
  },
  img: {
    width: 100,
    height: 100,
  },
});

上記の例で共有されている手順に関して、必要なすべての行の目的は既に指示されています。 この例では、container01container02、および container03container の子要素です。

アプリを実行すると、画面に以下の出力が表示されます。

出力:

React Native で要素を整列

上記で共有されたコードは React-Native で作成され、Expo-CLI を使用してアプリを実行したことに注意してください。