【问题标题】:How can i add a navigation drawer inside a stack navigator in an already existing project如何在现有项目的堆栈导航器中添加导航抽屉
【发布时间】:2022-01-02 12:34:21
【问题描述】:

大家好,我想在主屏幕中添加一个导航抽屉,但我不知道如何将它与现有的堆栈导航器嵌套, 这是我的导航组件:

import React from "react";
import { NavigationContainer } from "@react-navigation/native";
import { createStackNavigator } from "@react-navigation/stack";

import ProductsOverviewScreen from "../screens/shop/ProductsOverviewScreen";
import ProductDetails from "../screens/shop/ProductDetailScreen";
import { HeaderButtons,Item } from "react-navigation-header-buttons";
import HeaderButton from '../components/UI/HeaderButton'
import CartScreen from "../screens/shop/CartScreen";
import OrdersScreen from "../screens/shop/OrdersScreen";



const RootNavigation=()=> {
    const Stack = createStackNavigator();


    const NavigationDrawerStructure = (props)=> {
      //Structure for the navigatin Drawer
      const toggleDrawer = () => {
        //Props to open/close the drawer
        props.navigationProps.toggleDrawer();
      };
    
      return (
        <View style={{ flexDirection: 'row' }}>
          <TouchableOpacity onPress={()=> toggleDrawer()}>
            {/*Donute Button Image */}
            <Image
              source={{uri: 'https://raw.githubusercontent.com/AboutReact/sampleresource/master/drawerWhite.png'}}
              style={{ width: 25, height: 25, marginLeft: 5 }}
            />
          </TouchableOpacity>
        </View>
      );
    }

    const screenOptions ={
        headerShown:true,
        headerStyle: {
            backgroundColor: 'white',},
            headerTintColor: 'aqua',
          headerTitleStyle: {
            fontWeight: 'bold',
          },

    };

    return(
   
        <NavigationContainer>
        <Stack.Navigator initialRouteName='ProductsOverview' screenOptions={screenOptions}>
            <Stack.Screen name='ProductsOverview' component={ProductsOverviewScreen} options={({navigation,route})=>({title:'All Products',headerTitleStyle:{fontFamily:'open-sans-bold'},
            headerRight:()=>( <HeaderButtons HeaderButtonComponent={HeaderButton}><Item title ='Cart' iconName='md-cart' onPress={()=>{navigation.navigate('CartScreen')}}/></HeaderButtons>)})}/>
            <Stack.Screen name='ProductsDetail' component={ProductDetails} options={({route})=>({title:route.params.productTitle,headerTitleStyle:{fontFamily:'open-sans-bold'}})} />
            <Stack.Screen name='CartScreen' component={CartScreen} options={{title:'Cart Items', headerTitleStyle:{fontFamily:'open-sans-bold'}}} />
            <Stack.Screen name='OrdersScreen'  component={OrdersScreen} options={{title:'Orders '}}/> 
           </Stack.Navigator>
      
    </NavigationContainer>

    )
}

export default RootNavigation;

这是我的 app.js


import { StatusBar } from 'expo-status-bar';
import { StyleSheet } from 'react-native';
import {createStore , combineReducers} from 'redux';
import { Provider} from 'react-redux';
import AppLoading from 'expo-app-loading';
import * as Font from 'expo-font';
import productsReducer from './store/reducers/products';
import {composeWithDevTools} from 'redux-devtools-extension'
import RootNavigation from './navigation/ShopNavigation';
import cartReducer from './store/reducers/cart'
import { useState } from 'react';
import ordersReducer from './store/reducers/orders'


const rootReducer=combineReducers({
  products: productsReducer,
  cart: cartReducer,
  orders:ordersReducer,
});

const store = createStore(rootReducer,composeWithDevTools());

const fetchFonts=()=>{
  return Font.loadAsync({
    'open-sans': require('./assets/fonts/OpenSans-Regular.ttf'),
    'open-sans-bold': require('./assets/fonts/OpenSans-Bold.ttf')
  })
}

export default function App() {
  const [fontLoaded,setfontLoaded]= useState(false);
  
  if (!fontLoaded) {
    return (
      <AppLoading
        startAsync={fetchFonts}
        onFinish={()=>setfontLoaded(true)}
        onError={console.warn}
      />
    );
  }
  return (
    <Provider store={store}>
      <RootNavigation />
    </Provider>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});

你能告诉我如何将它们嵌套在一起吗?我尝试使用文档但仍然充满错误 谢谢

【问题讨论】:

    标签: javascript react-native


    【解决方案1】:

    Drawer Navigator 必须是 Stack 和 Tab 导航器的父级。有了这些知识,让我们重构我们的代码如下:

    import React from "react";
    import { NavigationContainer } from "@react-navigation/native";
    import { createStackNavigator } from "@react-navigation/stack";
    
    import ProductsOverviewScreen from "../screens/shop/ProductsOverviewScreen";
    import ProductDetails from "../screens/shop/ProductDetailScreen";
    import { HeaderButtons, Item } from "react-navigation-header-buttons";
    import HeaderButton from "../components/UI/HeaderButton";
    import CartScreen from "../screens/shop/CartScreen";
    import OrdersScreen from "../screens/shop/OrdersScreen";
    import { createDrawerNavigator } from "@react-navigation/drawer";
    
    const RootNavigation = () => {
      const Stack = createStackNavigator();
    
      const Drawer = createDrawerNavigator();
    
      const AppStack = () => (
        <Stack.Navigator
          initialRouteName="ProductsOverview"
          screenOptions={screenOptions}
        >
          <Stack.Screen
            name="ProductsOverview"
            component={ProductsOverviewScreen}
            options={({ navigation, route }) => ({
              title: "All Products",
              headerTitleStyle: { fontFamily: "open-sans-bold" },
              headerRight: () => (
                <HeaderButtons HeaderButtonComponent={HeaderButton}>
                  <Item
                    title="Cart"
                    iconName="md-cart"
                    onPress={() => {
                      navigation.navigate("CartScreen");
                    }}
                  />
                </HeaderButtons>
              ),
            })}
          />
          <Stack.Screen
            name="ProductsDetail"
            component={ProductDetails}
            options={({ route }) => ({
              title: route.params.productTitle,
              headerTitleStyle: { fontFamily: "open-sans-bold" },
            })}
          />
          <Stack.Screen
            name="CartScreen"
            component={CartScreen}
            options={{
              title: "Cart Items",
              headerTitleStyle: { fontFamily: "open-sans-bold" },
            }}
          />
          <Stack.Screen
            name="OrdersScreen"
            component={OrdersScreen}
            options={{ title: "Orders " }}
          />
        </Stack.Navigator>
      );
    
      return (
        <NavigationContainer>
          <Drawer.Navigator>
            <Drawer.Screen name="MainStack" component={AppStack} />
          </Drawer.Navigator>
        </NavigationContainer>
      );
    };
    
    export default RootNavigation;
    
    

    由于无法访问抽屉,我省略了下面的组件代码。

     const NavigationDrawerStructure = (props)=> {
          //Structure for the navigatin Drawer
          const toggleDrawer = () => {
            //Props to open/close the drawer
            props.navigationProps.toggleDrawer();
          };
        
          return (
            <View style={{ flexDirection: 'row' }}>
              <TouchableOpacity onPress={()=> toggleDrawer()}>
                {/*Donute Button Image */}
                <Image
                  source={{uri: 'https://raw.githubusercontent.com/AboutReact/sampleresource/master/drawerWhite.png'}}
                  style={{ width: 25, height: 25, marginLeft: 5 }}
                />
              </TouchableOpacity>
            </View>
          );
        }
    

    这里是工作实现的缩小版

    https://snack.expo.dev/@emmbyiringiro/69dc5b

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-09
    • 2018-03-26
    • 2022-06-30
    • 2019-12-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多