How to provide Picker a default “Please select…” option?

前端 未结 3 712
刺人心
刺人心 2021-02-07 14:49

I\'d like to make my Picker to show a \"default option\" on startup. That means: something like \"Please select an option\".

I\'ve tried to add a option manually with th

3条回答
  •  南方客
    南方客 (楼主)
    2021-02-07 15:35

    Here is how I just achieved it in React Native:

    InputPicker Presentational Component:

    import React from 'react'
    import { StyleSheet, View, Text, Picker } from 'react-native'
    
    const InputPicker = ({
        style,
        hasError,
        title,
        enabled,
        selectedValue,
        onValueChange,
        items,
        firstItem
    }) => {
        if (!items || !Array.isArray(items)) return null
    
        const { container, errorContainer, errorText, pickerTitle, pickerItem } = styles
    
        return (
            
                
                    {title}
                
    
                
    
                    
    
                    {items.map((c) => )}
                
            
        )
    }
    
    const styles = StyleSheet.create({
        container: {
            flex: 0,
            flexDirection: 'row',
            alignItems: 'center'
        },
        pickerTitle: {
            flex: 1,
            textAlign: 'right'
        },
        pickerItem: {
            flex: 2
        },
        errorContainer: {
            backgroundColor: '#F8DEE0',
            borderColor: '#DD0426',
            borderWidth: 1
        },
        errorText: {
            color: '#DD0426'
        }
    })
    
    export { InputPicker }
    

    Parent Container View (using Formik form handler)

    
         {
                this.props.setFieldValue('person_city', value)
                this.props.updateField({ prop: 'person_city', value })
            }}
            items={this.getCities()}
            firstItem="Select your city"
        />
    
    

    Parent Container this.getCities()

    getCities() {
        const cities = [
            { id: 0, label: 'Nanaimo' },
            { id: 1, label: 'Victoria' },
            { id: 2, label: 'Ladysmith' }
        ]
        return cities
    }
    

    It works because it sets value to 0 if "Select your city" is picked, which makes it a falsy value which triggers touched.person_city && errors.person_city and puts it into an error state.

提交回复
热议问题