React Native动态多次下拉(选择器)

时间:2017-12-17 06:39:14

标签: reactjs react-native dropdown

我想实现多个选择器,选择器的数量将基于我们在文本框中选择的值。 动态选择器(通过循环)中的问题是我无法正确使用Picker的“selectedValue”属性。无法动态设置Picker的值。

例如。代码,

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

let no_of_pickers = [1,2,3];//3 pickers can be increase or decreased
export default class App extends Component {
    constructor(props) {
        super(props)
        this.state = {
            selectValue = [0,0,0]
        };
    }

    setValue(value,index){
        let selectValue = this.state.selectValue;
        selectValue[index] = value;
        this.setState({
          selectValue:selectValue
        });//this won't set selected value on picker
    }
    render(){
        let pickers = no_of_pickers.map((value, i) => {
            return (
                <View key={i}>
                  <Picker
                    selectedValue={this.state.selectValue[i]}
                    onValueChange={(itemValue, itemIndex) => {this.setValue(itemValue, i)}}>
                      <Picker.Item value='0' label={'Select Value'} />
                      <Picker.Item value='1' label={'Value 1'} />
                      <Picker.Item value='2' label={'Value 2'} />
                      <Picker.Item value='3' label={'Value 3'} />
                  </Picker>
                </View>
            );
        });
        return (
            {pickers}
        );
    }
}

在上面的代码中,函数setValue应该在UI中设置选择器值,但只有状态值已更改但在UI中未选择值。

1 个答案:

答案 0 :(得分:0)

我喜欢使用react-native-smart-picker,因为当您.map数据时,vanilla RN不喜欢。

 render() {
    return (
        <ScrollView >
            <View style={{ flex: 1, marginTop: 20 }}>
                {this.state.models.length > 0 ?
                    <ScrollView >
                        <SmartPicker

                            expanded={this.state.expanded}
                            selectedValue={this.state.selectedModel}
                            label='Select Model'
                            onValueChange={this.handleChange.bind(this)}
                        >
                            {
                                this.state.models.map((ele) => {
                                    return (<Picker.Item label={ele} value={ele} />)
                                })
                            }
                            <Picker.Item label='Select Model' value='4Runner' />
                        </SmartPicker>
                        <Button block onPress={() => this.props.vehicleModel(this.state.selectedModel)}>
                            <Text>Done</Text>
                        </Button>
                    </ScrollView>
                    : <Spinner />}

            </View>

        </ScrollView>
    );
}