【问题标题】:Can't Navigate To Custom Screen - React Navigation?无法导航到自定义屏幕 - 反应导航?
【发布时间】:2019-09-20 06:18:15
【问题描述】:

我想从订单屏幕导航到主屏幕,但他的工作不太好,路线中的每个屏幕都可以工作,但主屏幕不,只是让我回到地图屏幕,我想要主屏幕而不是地图!!我已经告诉他们导航到主页。

这是我正在寻找的结构

主页 -> 地图 -> 订单,然后是订单 -> 主页

在主页中,我在代码下有侧边菜单抽屉检查。

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;

【问题讨论】:

  • 您的代码似乎可以正常工作snack.expo.io/@lekgwaraj/graceful-ramen
  • 在你的小吃中,它工作得很好,但在我的应用程序中不起作用,当我在订单屏幕上然后打开抽屉并单击主屏幕这将我移动到地图屏幕而不是主页!
  • 当我发送订单假定将我移至主屏幕时,它会再次将我带到地图
  • 我认为当我们没有功能齐全的Order 组件时,我们很难调试。我试过用你不能让它在零食上起作用。
  • @JuniusL。您没有考虑到地图屏幕,如果您在 MapApp 中添加一个按钮以移动到订单屏幕,并在订单中添加一个按钮以移动到主屏幕,您会看到问题。

标签: javascript reactjs react-native react-redux react-navigation


【解决方案1】:

您有两条名为“Home”的路线,一条在HomeDrawer,一条在DrawerNavigator。重命名DrawerNavigator 中的那个,它应该导航到正确的“主页”。

例如:

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

  },

【讨论】:

  • 很遗憾没有工作!
  • @DevAS 您是否重命名了密钥或drawerLabel?我已经更新了我的答案以显示您应该重命名的内容。
  • @zaytrix OH 是的,它的工作就像一个魅力,我有最后一个问题,如果我需要清除我在地图屏幕中传递的参数来订购,我真的在 订单屏幕 componentWillUnmount 但它没有被调用
  • 问题是当用户发送订单并转到主屏幕并选择一些类别时,他将发送具有不同参数的新订单我传递的不是以前的参数,如“Id-name”
  • @DevAS 尝试使用导航生命周期而不是组件生命周期:reactnavigation.org/docs/en/… 使用 willBlurdidBlur
【解决方案2】:

导出 Home.js 时,像这样导出它(使用 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);

【讨论】:

  • 为什么要这样做?
猜你喜欢
  • 1970-01-01
  • 2018-12-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-18
  • 1970-01-01
相关资源
最近更新 更多