React-native-listview

提供:Dev Guides
移動先:案内検索

React Native-ListView

この章では、React Nativeでリストを作成する方法を示します。 Home コンポーネントに List をインポートし、画面に表示します。

*App.js*
import React from 'react'
import List from './List.js'

const App = () => {
   return (
      <List/>
   )
}
export default App

リストを作成するには、* map()*メソッドを使用します。 これにより、アイテムの配列が反復処理され、各アイテムがレンダリングされます。

*List.js*
import React, { Component } from 'react'
import { Text, View, TouchableOpacity, StyleSheet } from 'react-native'

class List extends Component {
   state = {
      names: [
         {
            id: 0,
            name: 'Ben',
         },
         {
            id: 1,
            name: 'Susan',
         },
         {
            id: 2,
            name: 'Robert',
         },
         {
            id: 3,
            name: 'Mary',
         }
      ]
   }
   alertItemName = (item) => {
      alert(item.name)
   }
   render() {
      return (
         <View>
            {
               this.state.names.map((item, index) => (
                  <TouchableOpacity
                     key = {item.id}
                     style = {styles.container}
                     onPress = {() => this.alertItemName(item)}>
                     <Text style = {styles.text}>
                        {item.name}
                     </Text>
                  </TouchableOpacity>
               ))
            }
         </View>
      )
   }
}
export default List

const styles = StyleSheet.create ({
   container: {
      padding: 10,
      marginTop: 3,
      backgroundColor: '#d9f9b1',
      alignItems: 'center',
   },
   text: {
      color: '#4f603c'
   }
})

アプリを実行すると、名前のリストが表示されます。

ListView

リスト内の各アイテムをクリックして、名前でアラートをトリガーできます。

React Native ListView