我想实现多个选择器,选择器的数量将基于我们在文本框中选择的值。动态选择器(通过循环)中的问题是,我无法正确使用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中设置picker值,但只有状态值更改,但在UI中未选择值。
我喜欢使用react-native-smart-picker,因为香草rn不喜欢您的.map数据。
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>
);
}