问题描述
我创建了一个自定义 ModalContext.js
,但是当我触发按钮的 onPress
时,我的测试模式似乎没有显示
// ModalContext.js
import createDataContext from './createDataContext';
const modalReducer = (state,action) => {
switch (action.type) {
case 'openModal':
return { ...state,component: action.payload };
case 'hideModal':
return { ...state,component: null };
default:
return state;
}
};
const openModal = (dispatch) => (component) => {
console.log('hey there');
dispatch({ type: 'openModal',payload: component });
};
const hideModal = (dispatch) => () => {
dispatch({ type: 'hideModal' });
};
export const { Provider,Context } = createDataContext(
modalReducer,{
openModal,hideModal,},{ component: null }
);
// createDataContext.js
import React,{ useReducer } from 'react';
export default (reducer,actions,defaultValue) => {
const Context = React.createContext();
const Provider = ({ children }) => {
const [state,dispatch] = useReducer(reducer,defaultValue);
const boundActions = {};
for (let key in actions) {
boundActions[key] = actions[key](dispatch);
}
return (
<Context.Provider value={{ state,...boundActions }}>
{children}
</Context.Provider>
);
};
return { Context,Provider };
};
// App.js
const App = createAppContainer(navigator);
export default () => {
return (
<ModalProvider>
<AuthProvider>
<App
ref={(navigator) => {
setNavigator(navigator);
}}
/>
</AuthProvider>
</ModalProvider>
);
};
我在测试屏幕上有一个按钮来检查它是否有效。
// WebViewScreen.js
import React,{ useState,useContext } from 'react';
import { StyleSheet,Modal,View,Text,Button } from 'react-native';
import { Context as ModalContext } from '../context/ModalContext';
const WebViewScreen = ({ navigation }) => {
const { state,openModal } = useContext(ModalContext);
const errorModal = (
<View>
<Modal animationType='slide' visible={true}>
<View style={styles.centeredView}>
<View style={styles.modalView}>
<Text>Hello</Text>
</View>
</View>
</Modal>
</View>
);
return (
<>
<Button
onPress={() => {
openModal(errorModal);
}}
title='button'
/>
</>
);
};
WebViewScreen.navigationOptions = ({ navigation }) => {
return {
title: navigation.getParam('title'),};
};
const styles = StyleSheet.create({
view: {
backgroundColor: '#f1f3f4',centeredView: {
flex: 1,justifyContent: 'center',alignItems: 'center',marginTop: 22,modalView: {
margin: 20,backgroundColor: 'white',borderRadius: 20,padding: 35,shadowColor: '#000',shadowOffset: {
width: 0,height: 2,shadowOpacity: 0.25,shadowRadius: 4,elevation: 5,});
export default WebViewScreen;
它似乎实际上调用了该函数,因为我可以在控制台上看到 "hey there"
但没有出现模态。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)