是否可以连接两个选择器,以便当第一个选择器中有一个名称,而第二个选择器中有另一个名称时,它们会自动分配它们?
例如:用户具有first_name
和last_name
。当用户单击第一个选择器并选择first_name
时,将自动更改第二个选择器last_name
中的值。
答案 0 :(得分:0)
绝对可以,这是可能的。但是请考虑这两个名称需要相互关联的东西。我将为您提供一个示例,其中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>
);
}
如果您想看一看,我还创建了snack。希望我已经足够清楚了,我在这里的每一个澄清或建议。