English 中文(简体)
React Native - ListView
  • 时间:2024-12-27

React Native - ListView


Previous Page Next Page  

In this chapter, we will show you how to create a pst in React Native. We will import List in our Home component and show it on screen.

App.js

import React from  react 
import List from  ./List.js 

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

To create a pst, we will use the map() method. This will iterate over an array of items, and render each one.

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 ,
      apgnItems:  center ,
   },
   text: {
      color:  #4f603c 
   }
})

When we run the app, we will see the pst of names.

ListView

You can cpck on each item in the pst to trigger an alert with the name.

React Native ListView Advertisements