我在應用程式的許多螢屏上使用基本上如下所示的下拉選單。如您所見,在我使用此下拉選單的螢屏上,單擊時下拉選單的高度為 50,再次單擊時為 20。在我使用此下拉選單的螢屏上,如果下拉選單打開(高度為 50),我希望它在單擊螢屏上下拉選單以外的其他位置時關閉。由于我在這么多螢屏上使用下拉選單,我只想在下拉組件中執行此操作。我怎樣才能做到這一點?
import React, { useState } from 'react';
import { View, TouchableOpacity } from 'react-native';
export default Dropdown = () => {
const [isOpen, setIsOpen] = useState(false);
return (
<View
style={{ backgroundColor: "grey" }}>
<TouchableOpacity
style={{ height: 20, width: 200 }}
onPress={() => setIsOpen(prev => !prev)}>
</TouchableOpacity>
<View style={{
display: isOpen ? 'flex' : 'none',
height: 50
}}>
</View>
</View>
);
};
如何從下拉組件外部關閉自定義下拉串列
uj5u.com熱心網友回復:
您可以使用模式來顯示抽屜內容。這樣,您可以輕松地在使用它的螢屏上關閉抽屜。
import React, { useRef, useState } from 'react';
import { View, TouchableOpacity, Modal, TouchableWithoutFeedback, Text } from 'react-native';
export default Dropdown = () => {
const [isOpen, setIsOpen] = useState(false);
const [dropdownFrame, setDropdownFrame] = useState(null)
const dropdownRef = useRef()
const onPress = () => {
if (dropdownRef.current && dropdownRef.current.measure) {
dropdownRef.current.measure((fx, fy, width, height, x, y) => {
// required dropdown measure to display content directly below the dropdown
setDropdownFrame({ width, height, x, y })
setIsOpen(true)
})
}
}
return (
<View>
{/* drawer title */}
<TouchableOpacity
style={{ height: 30, backgroundColor: "grey" }}
onPress={onPress}
ref={dropdownRef}
>
<Text>Drawer Title</Text>
</TouchableOpacity>
{/* drawer content */}
{isOpen &&
<Modal transparent>
<TouchableWithoutFeedback onPress={() => setIsOpen(false)}>
<View style={{ flexGrow: 1 }}>
<View style={{
height: 40,
backgroundColor: "red",
top: dropdownFrame.y dropdownFrame.height,
left: dropdownFrame.x,
}} >
<Text>item</Text>
</View>
</View>
</TouchableWithoutFeedback>
</Modal>}
</View>
);
};
uj5u.com熱心網友回復:
可能你需要react-native-modal-dropdown
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/521105.html
