我使用Touchable Opacity
和Picker
创建了一个自定义Picker组件。单击可触摸的不透明度组件后,相关的选择器就会切换。我在具有不同数据的一个父中多次使用此组件。
选择器的切换状态isPickerOpen
在子组件中定义和使用,以降低父组件中状态管理的复杂性。我需要单击每个可触摸的不透明度以显示和隐藏其相关的选择器。
这是子组件的代码:
function CustomPicker(props) {
const {listItem, callbackParent} = props;
const [isPickerOpen, setPickerOpen] = useState(false);
const pickerListItem = listItems.map((item, i) => {
return <Picker.Item key={i} label={item.text} value={item.value} />
});
return (
<View>
<TouchableOpacity style={styles.pickerButton}
onPress={() => setPickerOpen(!isPickerOpen)}>
<Text>Title</Text>
</TouchableOpacity>
{isPickerOpen && <Picker onValueChange={(value) =>
callbackParent(value)}>
{pickerListItem}
</Picker>
}
</View>
);
}
和父成分分数:
<SelectionPicker listItems={list1} onPickerSelection={handleChange} />
<SelectionPicker listItems={list2} onPickerSelection={handleChange} />
<SelectionPicker listItems={list3} onPickerSelection={handleChange} />
如何通过单击可触摸不透明度来管理子组件的状态,如何隐藏所有其他打开的选择器,并仅显示一个相关的选择器?
答案 0 :(得分:1)
您需要添加一个外部变量以对Picker组件进行另一种形式的验证,如下所示:
function CustomPicker(props) {
const {
listItems,
onPickerClick,
onPickerSelection,
selectable = true,
name,
} = props;
//
const [isPickerOpen, setPickerOpen] = useState(false);
const pickerListItem = listItems.map((item, i) => {
return <Picker.Item key={i} label={item.text} value={item.value} />
});
return (
<View>
<TouchableOpacity
style={styles.pickerButton}
onPress={() => {
// calling our picker selection function
onPickerClick(name)
setPickerOpen(!isPickerOpen)
}}
>
<Text>Title</Text>
</TouchableOpacity>
{(isPickerOpen && selectable) && <Picker onValueChange={(value) =>
onPickerSelection(value, name)}>
{pickerListItem}
</Picker>
}
</View>
);
}
// Our selection handling function
handleSelection(name) {
this.setState({
currentPicker: name,
})
}
// Adding unique names, a validation prop, and a selection method
<SelectionPicker
name="someNameA"
selectable={'someNameA' === currentPicker}
onPickerClick={handleSelection}
onPickerSelection={handleChange}
listItems={list1}
/>
<SelectionPicker
name="someNameB"
selectable={'someNameB' === currentPicker}
onPickerClick={handleSelection}
onPickerSelection={handleChange}
listItems={list2}
/>
<SelectionPicker
name="someNameC"
selectable={'someNameC' === currentPicker}
onPickerClick={handleSelection}
onPickerSelection={handleChange}
listItems={list3}
/>