You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

@gorhom/bottom-sheet修改index为-1时无法关闭问题求助

问题:登录后Bottom Sheet无法关闭,打开正常

我配置了一个包含登录表单的bottom sheet,打开功能正常,但用户完成登录后,showAuthModal被设置为false,index也随之变为-1,bottom sheet却完全没有关闭。想问下这个问题是不是因为子组件调用Context导致的?

代码如下:

import { useContext, useMemo, useRef } from "react";
import { GeneralContext } from "@/providers";
import BottomSheet from "@gorhom/bottom-sheet";
import LoginForm from "./LoginForm";

const AuthSheet = () => {
  const { showAuthModal } = useContext(GeneralContext);

  const bottomSheetRef = useRef(null);
  // variables
  const snapPoints = useMemo(() => ["30%"], []);

  const index = useMemo(() => {
    if (showAuthModal) {
      return 0;
    }
    return -1;
  }, [showAuthModal]);

  return (
    <BottomSheet
      ref={bottomSheetRef}
      index={index}
      enablePanDownToClose={true}
      snapPoints={snapPoints}
    >
      <LoginForm />
    </BottomSheet>
  );
};

export default AuthSheet;
解决方案

这不是子组件调用Context导致的问题,核心原因是@gorhom/bottom-sheet对index从0切换到-1的状态变化可能没有正确触发关闭逻辑。以下是几种可行的解决办法:

  • 手动调用组件实例的关闭方法
    利用bottomSheetRef监听showAuthModal的变化,当它变为false时,直接调用组件的close()方法来触发关闭:

    import { useContext, useMemo, useRef, useEffect } from "react";
    import { GeneralContext } from "@/providers";
    import BottomSheet from "@gorhom/bottom-sheet";
    import LoginForm from "./LoginForm";
    
    const AuthSheet = () => {
      const { showAuthModal } = useContext(GeneralContext);
      const bottomSheetRef = useRef(null);
      const snapPoints = useMemo(() => ["30%"], []);
    
      useEffect(() => {
        if (!showAuthModal && bottomSheetRef.current) {
          bottomSheetRef.current.close();
        }
      }, [showAuthModal]);
    
      const index = useMemo(() => {
        return showAuthModal ? 0 : -1;
      }, [showAuthModal]);
    
      return (
        <BottomSheet
          ref={bottomSheetRef}
          index={index}
          enablePanDownToClose={true}
          snapPoints={snapPoints}
        >
          <LoginForm />
        </BottomSheet>
      );
    };
    
    export default AuthSheet;
    
  • 检查Context状态更新的正确性
    确认登录完成后showAuthModal确实被正确更新,并且Context的状态变化触发了AuthSheet组件的重渲染。可以在组件内添加console.log(showAuthModal),查看状态是否正常传递。

  • 调整index的取值逻辑
    尝试将index的返回值改为showAuthModal ? 0 : undefined,部分场景下这种取值方式更符合组件的状态切换预期:

    const index = useMemo(() => {
      return showAuthModal ? 0 : undefined;
    }, [showAuthModal]);
    

内容的提问来源于stack exchange,提问作者Bowis

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 23:45:47