React Navigation5.0系列三:Drawer navigation的使用

首先祝你們五四青年節及五一假期快樂。
在前面系列文章中咱們瞭解5.0最新版本堆棧導航和選項卡導航的用法,今天咱們來看看抽屜導航的使用方法。
React Navigation5.0系列一:StackNavigator的使用
React Navigation5.0系列二:TabNavigation的使用
@[toc]node

安裝

yarn add @react-navigation/drawer

使用

1.導入對應的組件
import { createDrawerNavigator } from '@react-navigation/drawer'

2.建立兩個頁面
const SettingsScreen = ({ navigation }) => {
  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Text>SettingScreen</Text>
      <Button
        title="Go to Details"
        onPress={() => navigation.navigate('Home')}
      />
    </View>
  )
}

const HomeScreen = ({ navigation }) => {
  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Text>HomeScreen</Text>
      <Button
        title="Go to Details"
        onPress={() => navigation.navigate('Setting')}
      />
    </View>
  )
}

3.建立drawer導航器實例
const Drawer = createDrawerNavigator();

4.在AppContainer中進行集成
const App = () => {
  return (
    <NavigationContainer>
      <Drawer.Navigator initialRouteName="Home">
        <Drawer.Screen name='Home' component={HomeScreen} />
        <Drawer.Screen name='Setting' component={SettingsScreen} />
      </Drawer.Navigator>
    </NavigationContainer>
  );
}

實現效果

在這裏插入圖片描述
Drawer navigation的簡單使用就是這樣了,接下來說解一下組件的打開與關閉及判斷當前狀態的判斷方法。
打開和關閉Drawer的方法:react

navigation.openDrawer();
navigation.closeDrawer();

或者也能夠經過派發一些action的方式來進行打開或者關閉npm

navigation.dispatch(DrawerActions.openDrawer());
navigation.dispatch(DrawerActions.closeDrawer());
navigation.dispatch(DrawerActions.toggleDrawer());

經過以下的方式,能夠判斷當前的drawer的開關狀態,在你須要的的時候json

import { useIsDrawerOpen } from '@react-navigation/drawer';

const isDrawerOpen = useIsDrawerOpen();

抽屜導航還有許多屬性能夠進行配置,詳細的看:https://reactnavigation.org/d...ide

Drawer Navigator屬性介紹

    • initialRouteName 設置首次加載默認的第一個頁面路由名字
    • screenOptions 設置頁面的選項
    • openByDefault 默認的抽屜打開狀態
    • drawerPosition 設置抽屜打開的位置,值爲’left'和‘right', 默認是left
    • drawerType 抽屜打開的方式和動畫flex

      • font 經常使用的默認效果動畫
      • back 隱藏也頁面後面,滑動時顯示
      • slide 頁面和抽屜一塊兒滑動時顯示drawer
      • permanent 一直在屏幕邊緣存在,這個在大屏幕上比較實用
    • drawerStyle 設置抽屜的樣式
    • drawerContent 設置抽屜的內容選項,提供了DrawerItem對象用來設置各個導航項以及drawerContentOptions來配置相關導航選項的樣式

    ......
    等等屬性內容,能夠經過上面的地址仔細閱讀動畫

    集成出現的問題

    1.使用drawer navigation導航報錯:undefined is not a function (near '...createRouter...')
    在這裏插入圖片描述
    解決方式:升級依賴spa

    yarn upgrade @react-navigation/native

    2.上面升級後報錯:"SyntaxError in @react-navigation/xxx/xxx.tsx" or "SyntaxError: /xxx/@react-navigation/xxx/xxx.tsx: Unexpected token"
    在這裏插入圖片描述
    解決方法:刪除node_modules 及 lock文件,從新安裝便可.net

    If you use npm:code

    rm -rf node_modules
    rm package-lock.json
    npm install

    If you use yarn:

    Copy
    rm -rf node_modules
    rm yarn.lock
    yarn

    今天就介紹這些吧,若是問題歡迎在評論區留言,和我一塊兒交流。

    歡迎關注個人公衆號:君偉說。分享移動開發技術與職場生活。

    相關文章
    相關標籤/搜索