React Native Multiple BottomSheets with useRef and forwardRef from ContextProvider - (Error: Right operand of 'in' is not an object)

问题描述 投票:0回答:0

我创建了一个上下文提供程序,它循环遍历 BottomSheets(模式)数组,为每个工作表创建一个引用,然后使用 forwardRef 将引用传递给每个工作表/模式。我已经通过供应商提供了 handleShowModal 功能,以便在按钮组件中使用。

有更好的方法吗?我尝试过的一切都失败了,错误是:

“in”的右操作数不是对象

这是我的 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;

javascript reactjs react-native expo bottom-sheet
© www.soinside.com 2019 - 2024. All rights reserved.