是否可以连接两个选择器,以便在第一个中有一个名称而第二个中有一个名称时,它会自动分配它们?
例如:用户有first_name
和last_name
。当用户单击第一个选取器并选择first_name
自动更改第二个选取器last_name
中的值时。
绝对是的,这是可能的。但考虑到这两个名字需要一些相互关联的东西。我将给你一个例子,其中state
处理一个names
数组和一个pickedName
,这是两个选取器将要显示的值。这两个选取器只是将不同的标签映射到相同的值。
state={
pickedName: {
firstName: '',
lastName: ''
},
names: [
{
firstName: 'Pinco',
lastName: 'Pallino'
},
{
firstName: 'Mario',
lastName: 'Rossi'
}
]
}
render() {
const { pickedName } = this.state;
return (
<View style={styles.container}>
<Picker
selectedValue={pickedName}
style={{ height: 50, width: 100 }}
onValueChange={(itemValue, itemIndex) =>
this.setState({ pickedName: itemValue })
}>
{this.state.names.map(name => (
<Picker.Item label={name.firstName} value={name} />
))}
</Picker>
<Picker
selectedValue={pickedName}
style={{ height: 50, width: 100 }}
onValueChange={(itemValue, itemIndex) =>
this.setState({ pickedName: itemValue })
}>
{this.state.names.map(name => (
<Picker.Item label={name.lastName} value={name} />
))}
</Picker>
</View>
);
}
更新:假设您在屏幕安装期间从数据库中获取名称。你可以这样做:
state = {
pickedName: {
firstName: '',
lastName: '',
},
names: [],
};
componentDidMount() {
this.getNamesFromDB();
}
getNamesFromDB = () => {
// Here you can call DB to get names list.
// So the following const wouldn't be hardcoded as I did
const nameList = [
{
firstName: 'Pinco',
lastName: 'Pallino',
},
{
firstName: 'Mario',
lastName: 'Rossi',
},
];
// set the component state with the list you've received
// (by default pickers show the first element of the list, so you don't need to specify pickedName,
// but if you want to select another element you can do it this way)
this.setState({
names: nameList,
// pickedName: nameList[1] // <-- to select the second element by default
});
}
render() {
const { pickedName } = this.state;
return (
<View style={styles.container}>
<Picker
selectedValue={pickedName}
style={{ height: 50, width: 200 }}
mode={'dropdown'}
onValueChange={(itemValue, itemIndex) =>
this.setState({ pickedName: itemValue })
}>
{this.state.names.map(name => (
<Picker.Item label={name.firstName} value={name} />
))}
</Picker>
<Picker
selectedValue={pickedName}
style={{ height: 50, width: 200 }}
mode={'dropdown'}
onValueChange={(itemValue, itemIndex) =>
this.setState({ pickedName: itemValue })
}>
{this.state.names.map(name => (
<Picker.Item label={name.lastName} value={name} />
))}
</Picker>
</View>
);
}
如果你想看一看,我还做了一个小吃。希望我已经足够清楚了,我在这里进行每一个澄清或建议。