React Native多BottomSheet用useRef/forwardRef报错:'in'右操作数非对象
问题描述
我创建了一个ContextProvider,遍历BottomSheet(Modal)数组,为每个Sheet创建ref并通过forwardRef传递给对应的Sheet/Modal,同时将handleShowModal函数通过Provider暴露给按钮组件调用,但所有尝试均失败,出现报错:
Right operand of 'in' is not an object
我的ContextProvider(SheetContextProvider)- 省略导入
const modals = [ { name: 'wallet', component: WalletModal, snapPoints: '45%' }, { name: 'shipping', component: ShippingModal, snapPoints: '45%' }, { name: 'listings', component: ListingsModal, snapPoints: '90%' }, ]; export default function SheetContextProvider({ children }) { const refs = useRef([]); const handleShowModal = useCallback((index) => { refs.current[index].present(); }, []); const value = { handleShowModal }; return ( <BottomSheetModalProvider> <SheetContext.Provider value={value}> {children} {modals.map((item, index) => { const Modal = item.component; return <Modal ref={(element) => (refs.current[index] = element)} key={index} />; })} </SheetContext.Provider> </BottomSheetModalProvider> ); }
调用handleShowModal的按钮组件
// Sheet index is referenced from sheets array in SheetContextProvider const SHEET_INDEX = 1; const LISTINGS_TEXT = 'Listings'; export default function ListingsAction() { const { handleShowModal } = useSheetContext(); return ( <Pressable onPress={() => handleShowModal(SHEET_INDEX)} style={styles.action}> <MaterialIcons name="storefront" size={22} color="white" style={styles.icon} /> <Text style={styles.text}>{LISTINGS_TEXT}</Text> </Pressable> ); }
点击按钮应打开的BottomSheet Modal
const ListingsModal = forwardRef(function ({}, ref) { const snapPoints = '45%'; const listingsRef = useRef(null); useImperativeHandle(ref, () => { return { present() { listingsRef.current.present(); }, }; }); return ( <BottomSheetModal ref={listingsRef} index={0} snapPoints={snapPoints} style={styles.container} backgroundStyle={styles.background} handleIndicatorStyle={styles.handle} > <View> <Text>Listings Sheet</Text> </View> </BottomSheetModal> ); }); export default ListingsModal;
请问是否有更优的实现方式?
内容的提问来源于stack exchange,提问作者Jayson H
相关产品推荐
相关产品推荐

