React Native中的应用程序范围的模态



我目前使用的是react原生模态,它用于显示模态。

我目前的问题是,我想在整个应用程序中展示模态。例如,当收到推送通知时,无论用户在哪个屏幕上,我都想调用模态。模态的当前设计将其绑定到一个屏幕上。

如何克服这一点?

首先创建模式的上下文

const BottomModal = React.createContext();

然后使用reactcontext提供商提供您的模式



export const BottomModalProvider = ({children}) => {
const panelRef = useRef();
const _show = useCallback((data, type) => {
panelRef.current.show();
}, []);
const _hide = useCallback(() => {
panelRef.current.hide();
}, []);

const value = useMemo(() => {
return {
_show,
_hide,
};
}, [_hide, _show]);
return (
<BottomPanelContext.Provider value={value}>
{children}
<BottomPanel fixed ref={panelRef} />
</BottomPanelContext.Provider>
);
};

这是底部面板的代码


function BottomPanel(props, ref) {
const {fixed} = props;
const [visible, setVisibility] = useState(false);
const _hide = () => {
!fixed && hideModal();
};
const hideModal = () => {
setVisibility(false);
};
useImperativeHandle(ref, () => ({
show: () => {
setVisibility(true);
},
hide: () => {
hideModal();
},
}));
return (
<Modal
// swipeDirection={["down"]}
hideModalContentWhileAnimating
isVisible={visible}
avoidKeyboard={true}
swipeThreshold={100}
onSwipeComplete={() => _hide()}
onBackButtonPress={() => _hide()}
useNativeDriver={true}
style={{
justifyContent: 'flex-end',
margin: 0,
}}>
<Container style={[{flex: 0.9}]}>
{!fixed ? (
<View style={{flexDirection: 'row', justifyContent: 'flex-end'}}>
<Button
style={{marginBottom: 10}}
color={'white'}
onPress={() => setVisibility(false)}>
OK
</Button>
</View>
) : null}
{props.renderContent && props.renderContent()}
</Container>
</Modal>
);
}
BottomPanel = forwardRef(BottomPanel);
export default BottomPanel;

然后使用提供商包装您的应用程序

...
<BottomModalProvider>
<NavigationContainer screenProps={screenProps} theme={theme} />
</BottomModalProvider>
...

最后,如何显示或隐藏模态提供自定义挂钩

const useBottomPanel = props => {
return useContext(BottomPanelContext);
};

在等应用程序中的任何位置使用


const {_show, _hide} = useBottomModal();
//....
openModal=()=> {
_show(); 
}
//...

如果您不使用钩子或类组件您可以使用类上下文轻松转换挂钩

https://reactjs.org/docs/context.html#reactcreatecontext

通过这种方式,您可以实现仅显示组件中的模态另一种方法是将面板引用全局存储在任何位置,并使用该引用来显示对非组件文件(如redux或通知案例(的隐藏。

最新更新