【问题标题】:Close bottom sheet on pressing back button on android在android上按下后退按钮时关闭底部工作表
【发布时间】:2022-06-20 14:54:56
【问题描述】:

我在 react native expo 中使用 @gorhom/bottom-sheet 库,我想在按下 android 上的后退按钮时关闭工作表,我该如何实现?

【问题讨论】:

    标签: react-native expo bottom-sheet


    【解决方案1】:

    在你的 useEffect 中创建一个 backHandler 事件并在其中调用 bottomSheetRef.current.close() 方法:-

    useEffect(() => {
        const backAction = () => {
         bottomSheetRef.current.close()
          return true;
        };
    
        const backHandler = BackHandler.addEventListener(
          "hardwareBackPress",
          backAction
        );
    
        return () => backHandler.remove();
        }, []);
    

    【讨论】:

    • 非常感谢,一切正常
    【解决方案2】:

    在按下后退按钮时反应原生元素底部工作表

      const sheetRef = useRef<BottomSheet>(null);
      const snapPoints = useMemo(() => ["%100", "20%"], []);
      const [isShowing, setIsShowing] = useState<boolean>(false);
    
    useFocusEffect(
        useCallback(() => {
          const onBackPress = () => {
            if (isShowing) {
              sheetRef.current?.close();
              return true;
            } else if (!isShowing) {
              navigation.goBack();
              return true;
            }
          };
          BackHandler.addEventListener("hardwareBackPress", onBackPress);
          return () =>
            BackHandler.removeEventListener("hardwareBackPress", onBackPress);
        }, [sheetRef, isShowing])
      );
    
    
    
         
    
      <BottomSheet
        ref={sheetRef}
        snapPoints={snapPoints}
        enablePanDownToClose={true}
        onChange={(idx) => {
        setIsShowing(idx < 1 ? false : true);
        }}
        backdropComponent={BottomSheetBackdrop}
        >
          <BottomSheetView>
            <Text>Awesome ?</Text>
          </BottomSheetView>
       </BottomSheet>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多