[RN] 如何不讓使用者回上一頁

張庭瑋
3 min readJul 17, 2021

*這裡使用的是 react-navigation

這裡講的回上一頁都是在說按 Android的 soft menu的上一頁或是使用 ios的手勢,至於 App裡 header的上一頁箭頭是可以隱藏的,這裡就不討論

  1. reset
import { CommonActions } from '@react-navigation/native';navigation.dispatch(  CommonActions.reset({    index: 1,    routes: [      { name: 'Home' },      {        name: 'Profile',        params: { user: 'jane' },      },    ],  }));

然而由於 reset的概念是清空 history後使用自己設定的 history,如果只是想不讓這個頁面返回,下一個頁面還是能用 navigate返回的話這個方式就行不通

If the screen is already present in the stack’s history, it’ll go back to that screen and remove any screens after that.

2. push之後鎖住 go back

單個頁面鎖住 go back就是這篇的重點了,ios 跟 android的實現方式有所不同

Ios

在 screen的 option增加 gestureEnabled

<Stack.Screen  name="screenName"  component={ScreenComponent}  options={{gestureEnabled: false}}/>

如果想鎖住 Stack也可以

<Stack.Navigator
screenOptions={{
gestureEnabled: false,
}}
>
...
</Stack.Navigator>

這裡的鎖住手勢只會鎖 swipe,所以點擊依舊 ok

Android

Custom Android back button behavior,這裡可以簡單地寫個 hook讓使用起來比較方便

import {useFocusEffect} from '@react-navigation/native';import {useCallback} from 'react';import {BackHandler} from 'react-native';export default function usePreventGoingBack(onBackPress = () => true) {  useFocusEffect(    useCallback(      () => {        BackHandler.addEventListener('hardwareBackPress',  
onBackPress);
return () => BackHandler.removeEventListener('hardwareBackPress',
onBackPress);
}, [onBackPress], ), );}

使用時的話直接在 component內調用

...export default ScreenComponent(){
usePreventGoingBack()
...
}

就能鎖住 go back了

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

No responses yet

Write a response