简体   繁体   中英

Can't Navigate To Custom Screen - React Navigation?

I want to navigate from Order screen To Home Screen but he doesn't work very well, every screen in the route is work, But Home screen Nope, Just back me to the Map screen, And I want Home Screen Not Map !! I already tell them to navigate to Home.

Here is structure I'm Dowing

Home -> Map -> Order, then Order -> Home

and in the Home, I have side menu Drawer check under the code.

Route.js

import React, { Component } from 'react';
import {
  View,
  TouchableOpacity,
} from 'react-native';

//Import required react-navigation component 
import {
  createDrawerNavigator,
  createStackNavigator,
  createAppContainer,
  createSwitchNavigator
} from 'react-navigation';

//Import all the screens for Drawer/ Sidebar
import Home from "../screens/Home";
import Splash from "../screens/Splash";
import SignUp from "../screens/SignUp";
import SignIn from "../screens/SignIn";
import ForgetPassword from "../screens/ForgetPassword";
import Order from "../screens/Order";
import MapApp from "../screens/MapApp";
import Profile from "../screens/Profile";


import Icon from 'react-native-vector-icons/Ionicons';

//Navigation Drawer Structure for all screen
class NavigationDrawerStructure extends Component {
  //Structure for the navigatin Drawer
  toggleDrawer = () => {
    //Props to open/close the drawer
    this.props.navigationProps.toggleDrawer();
  };
  render() {
    return (
      <View style={{ flexDirection: 'row' }}>
        <TouchableOpacity onPress={this.toggleDrawer.bind(this)}>
          <Icon name="md-menu" size={30} color='#fff' style={{ marginLeft: 10 }} />
        </TouchableOpacity>
      </View>
    );
  }
}

// Stack Navigator for app
const AuthStackNavigator = createStackNavigator({
  //All the screen from the Screen1 will be indexed here
  SignUp: {
    screen: SignUp,
    navigationOptions: () => ({
      // header: null
      title: "Sign Up",
      headerLeft: null,
      headerTintColor: "#0496FF",
      headerStyle: {
        borderBottomColor: "white"
      },
      headerTitleStyle: {
        color: "#0496FF",
        textAlign: "center",
        flex: 1,
        elevation: 0,
        fontSize: 25,
        justifyContent: "center"
      }
    })
  },
  SignIn: {
    screen: SignIn,
    navigationOptions: {
      title: "Sign In",
      headerRight: <View />,
      headerTintColor: "#0496FF",
      headerStyle: {
        borderBottomColor: "white"
      },
      headerTitleStyle: {
        color: "#0496FF",
        textAlign: "center",
        flex: 1,
        elevation: 0,
        fontSize: 25,
        justifyContent: "center"
      }
    }
  },
  ForgetPassword: {
    screen: ForgetPassword,
    navigationOptions: {
      title: "Forget Password",
      headerRight: <View />,
      headerTintColor: "#0496FF",
      headerStyle: {
        borderBottomColor: "white"
      },
      headerTitleStyle: {
        color: "#0496FF",
        textAlign: "center",
        flex: 1,
        elevation: 0,
        fontSize: 25,
        justifyContent: "center"
      }
    }
  },

});

//Stack Navigator for First Option of Navigation Drawer
const HomeDrawer = createStackNavigator({
  Home: {
    screen: Home,
    navigationOptions: ({ navigation }) => ({
      title: 'Home',
      headerLeft: <NavigationDrawerStructure navigationProps={navigation} />,
      headerRight: <View />,
      headerStyle: {
        backgroundColor: '#258fdb',
        shadowOpacity: 0,
        elevation: 0,
        marginBottom: 20
      },
      headerTintColor: '#fff',
      headerTitleStyle: {
        textAlign: "center",
        flex: 1,
        elevation: 0,
        fontSize: 25,
        justifyContent: "center"
      }
    }),
  },
  MapApp: {
    screen: MapApp,
    navigationOptions: {
      title: "Map",
      headerRight: <View />,
      headerLeft: <View />,
      headerTintColor: "#fff",
      headerStyle: {
        backgroundColor: "#258fdb",
        borderBottomColor: "white",
      },
      headerTitleStyle: {
        textAlign: "center",
        flex: 1,
        elevation: 0,
        fontSize: 25,
        justifyContent: "center"
      }
    }
  }
});

//Stack Navigator for Second Option of Navigation Drawer
const OrderDrawer = createStackNavigator({
  Order: {
    screen: Order,
    navigationOptions: ({ navigation }) => ({
      title: 'Order',
      headerLeft: <NavigationDrawerStructure navigationProps={navigation} />,
      headerStyle: {
        backgroundColor: '#258fdb',
      },
      headerTintColor: '#fff',
    }),
  },
});
const ProfileDrawer = createStackNavigator({
  Profile: {
    screen: Profile,
    navigationOptions: ({ navigation }) => ({
      title: 'Profile',
      headerLeft: <NavigationDrawerStructure navigationProps={navigation} />,

      headerStyle: {
        backgroundColor: '#258fdb',
      },
      headerTintColor: '#fff',
    }),
  },
})
//Drawer Navigator for the Navigation Drawer / Sidebar
const DrawerNavigator = createDrawerNavigator({
  Home: {
    screen: HomeDrawer,
    navigationOptions: {
      drawerLabel: 'Home',
      drawerIcon: () => (
        <Icon name="ios-home" size={30} color='#0496FF' />
      ),
    },

  },
  Order: {
    screen: OrderDrawer,
    navigationOptions: {
      drawerLabel: 'Order',
      drawerIcon: () => (
        <Icon name="ios-list-box" size={30} color='#0496FF' />
      ),
    },
  },
  Profile: {
    screen: ProfileDrawer,
    navigationOptions: {
      drawerLabel: 'Profile',
      drawerIcon: () => (
        <Icon name="ios-contact" size={30} color='#0496FF' />
      ),
    },
  },
});

const Navigations = createSwitchNavigator({
  Authloading: Splash,
  Auth: AuthStackNavigator, // the Auth stack
  App: DrawerNavigator, // the App stack
})

export default MyApp = createAppContainer(Navigations);

Order.js

import React, { Component } from 'react';
import styles from "../Style/styles";
import firebase from "react-native-firebase";
import ImagePicker from "react-native-image-picker";
import { View, Text, StyleSheet, TextInput, ScrollView, KeyboardAvoidingView, TouchableOpacity, Image } from 'react-native';

// create a component

class Order extends Component {
    constructor(props) {
        super(props);
        this.state = {
            userId: null,
            nameOfProblem: '',
            description: '',
            imageOfPrblem: '',
            timeDate: {},
            providerId: this.props.navigation.dangerouslyGetParent().getParam('providerId'),
        }
    }
    componentDidMount() {
        const userId = firebase.auth().currentUser.uid;
        this.setState({ userId });
    }
    handleOrder = () => {
        const { nameOfProblem, description, userId, imageOfPrblem, providerId } = this.state;
        const PushData = firebase.database().ref("request/" + providerId + "/" + userId + "/orders/");
        const ref = firebase.storage().ref("users/" + userId + "/UserImageOrders/" + path);
        let file = imageOfPrblem.uri;
        const path = "img_" + imageOfPrblem.fileName;
        if (file) {
            return (
                PushData.update({
                    nameOfProblem: nameOfProblem,
                    description: description,
                    // ...this.state.nameOfProblem,
                    // ...this.state.description,
                    imageOfPrblem: imageOfPrblem
                }).then(() => {
                    ref.put(file).then(() => {
                        console.log("File uploaded..")
                        setTimeout(() => {
this.props.navigation.navigate("Home"); // not working and get me back to Map screen, but when i navigate to other screen it's work fine!
                        }, 3000);
                    });
                })
            )
        }
        else {
            return (
                PushData.push({
                    nameOfProblem: nameOfProblem,
                    description: description,
                }).then(() => {
                    setTimeout(() => {
                        this.props.navigation.navigate("Home"); // Not work
                    }, 3000);
                })
            )
        }
        // else {

        // }
    }

    handleImages = () => {
        const options = {
            title: "Select Images!",
            storageOptions: {
                skipBackup: true,
                path: "images"
            }
        };
        ImagePicker.showImagePicker(options, response => {
            console.log("Response = ", response);
            if (response.uri) {
                this.setState({ imageOfPrblem: response });
            }
            if (response.didCancel) {
                console.log("User cancelled image picker");
            } else if (response.error) {
                console.log("ImagePicker Error: ", response.error);
            } else if (response.customButton) {
                console.log("User tapped custom button: ", response.customButton);
                alert(response.customButton);
            }
        });
    };

    render() {
        const { nameOfProblem, description, imageOfPrblem, timeDate } = this.state;
        const { getParam } = this.props.navigation.dangerouslyGetParent();
        const providerId = getParam('providerId');
        const providerName = getParam('providerName');
        return (
            <ScrollView scrollEnabled={true}>
                <KeyboardAvoidingView behavior="padding" keyboardVerticalOffset={70}>
                    <View style={[styles.container, { marginTop: 20 }]}>
                        <Text>Send Order To: {JSON.stringify(providerName)}, ID:{JSON.stringify(providerId)}</Text>

                        <TextInput
                            style={styles.textInput}
                            placeholder="Name of Problem"
                            value={nameOfProblem}
                            onChangeText={(nameOfProblem) => this.setState({ nameOfProblem })}
                            returnKeyType="next"
                            returnKeyLabel="next"
                        />

                        <TextInput
                            style={[styles.textInput, {
                                borderRadius: 5,
                                borderWidth: 1,
                                height: 120,
                                fontSize: 16,
                                padding: 10,
                                marginTop: 8
                            }]}
                            placeholder="Description"
                            multiline={true}
                            numberOfLines={12}
                            textAlignVertical="top"
                            value={description}
                            onChangeText={(description) => this.setState({ description })}
                            returnKeyType="next"
                            returnKeyLabel="next"
                        />

                        <TouchableOpacity onPress={this.handleImages}>
                            <View
                                style={{
                                    backgroundColor: "#DBDBDB",
                                    borderRadius: 100,
                                    alignSelf: "center",
                                    margin: 10,
                                    paddingBottom: 2,
                                    width: 120,
                                    height: 120
                                }}
                            >
                                <Text
                                    style={{
                                        position: "absolute",
                                        zIndex: 1,
                                        fontSize: 40,
                                        top: 67,
                                        color: "#1567d3",
                                        left: 99
                                    }}
                                >
                                    +
                                </Text>
                                <Image
                                    source={{ uri: imageOfPrblem.uri }}
                                    style={[styles.uploadAvatar, { borderRadius: 100 }]}
                                    resizeMode="cover"
                                />

                            </View>
                        </TouchableOpacity>
                        <TouchableOpacity
                            style={[styles.button, { backgroundColor: "#1567d3" }]}
                            onPress={this.handleOrder}
                        >
                            <Text style={{ color: "#fff", fontSize: 18 }}>Send</Text>
                        </TouchableOpacity>
                    </View>
                </KeyboardAvoidingView>
            </ScrollView>
        );
    }

}

// define your styles

//make this component available to the app
export default Order;

You have two routes with the name "Home", one in HomeDrawer and one in DrawerNavigator . Rename the one in DrawerNavigator and it should navigate to the correct "Home".

For example:

HomeDrawer: { // renamed this from Home to HomeDrawer
    screen: HomeDrawer,
    navigationOptions: {
      drawerLabel: 'Home',
      drawerIcon: () => (
        <Icon name="ios-home" size={30} color='#0496FF' />
      ),
    },

  },

When exporting Home.js, export it like this (using withNavigation ).

import React, { Component } from 'react'
import { Text, View } from 'react-native'
import { withNavigation } from 'react-navigation';

class Home extends Component {
  render() {
    return (
      <View>
        <Text> Home </Text>
      </View>
    )
  }
}

export default withNavigation(Home);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM