使用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方法:
- 修改
bottomSheetRef的声明,添加泛型类型:
// 直接指定泛型为BottomSheet组件类型,初始值设为null const bottomSheetRef = useRef<BottomSheet>(null);
- 如果库未直接导出
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
相关产品推荐
相关产品推荐

