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

使用react-native-simple-bottom-sheet时遇'togglePanel不存在于never类型'错误

解决React Native中react-native-simple-bottom-sheet的togglePanel类型错误

你遇到的错误Property 'togglePanel' does not exist on type 'never'是TypeScript的类型推断问题:当你未给useRef指定泛型类型时,TypeScript会默认将其推断为never类型,导致无法识别current上的togglePanel方法。

解决方案

给useRef明确指定BottomSheet组件的实例类型,让TypeScript能识别ref指向的对象包含togglePanel方法:

  1. 修改bottomSheetRef的声明,添加泛型类型:
// 直接指定泛型为BottomSheet组件类型,初始值设为null
const bottomSheetRef = useRef<BottomSheet>(null);
  1. 如果库未直接导出BottomSheet类型,可通过InstanceType获取组件实例类型:
const bottomSheetRef = useRef<InstanceType<typeof BottomSheet>>(null);

修改后的关键代码片段

const SpaceBottomSheet = ({ onClose }: SpaceBottomSheetProps) => {
    // 明确指定ref的类型
    const bottomSheetRef = useRef<BottomSheet>(null);
    // 同时建议给useState也指定类型,提升代码规范性
    const [expandedItem, setExpandedItem] = useState<number | null>(null);
    
    const closeBottomSheet = () => {
        if (bottomSheetRef.current) {
            bottomSheetRef.current.togglePanel();
            onClose();
        }
    };
    // ... 其他代码
};

原理说明

TypeScript需要明确知道ref引用的组件实例类型,否则会使用最严格的never类型进行校验,导致无法访问实例方法。通过指定泛型类型,TypeScript能正确识别bottomSheetRef.current的结构,允许调用togglePanel方法。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 13:14:57