React Native - Picker

在本章中,我们将创建具有两个可用选项的简单 Picker。

步骤 1:创建文件

此处,App.js 文件夹将用作展示组件。

App.js

import React from 'react'
import PickerExample from './PickerExample.js'

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

步骤 2:逻辑

this.state.user 用于选择器控制。

选择用户时将触发 updateUser 函数。

PickerExample.js

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

class PickerExample extends Component {
   state = {user: ''}
   updateUser = (user) => {
      this.setState({ user: user })
   }
   render() {
      return (
         <View>
            <Picker selectedValue = {this.state.user} onValueChange = {this.updateUser}>
               <Picker.Item label = "Steve" value = "steve" />
               <Picker.Item label = "Ellen" value = "ellen" />
               <Picker.Item label = "Maria" value = "maria" />
            </Picker>
            <Text style = {styles.text}>{this.state.user}</Text>
         </View>
      )
   }
}
export default PickerExample

const styles = StyleSheet.create({
   text: {
      fontSize: 30,
      alignSelf: 'center',
      color: 'red'
   }
})

输出

React Native Picker

如果您单击名称,它会提示您所有三个选项为 −

React Native Picker

您可以选择其中一个,输出将如下所示。

React Native Picker