React Native Navigation 覆盖 Stack Navigator 中标题后退按钮的 goBack()

Dav*_*ide 8 reactjs react-native react-navigation-stack

我想将堆栈导航器中默认后退按钮的行为本地自定义到一个屏幕。

在详细信息中,假设堆栈上有 screen1|screen2,我想在按下按钮后将一些道具从 screen2 传递到 screen1。

我花了很多时间阅读 React 导航文档、在互联网上搜索和编码,但我无法做到这一点。

来自文档

在某些情况下,您可能希望比通过上述选项更多地自定义后退按钮,在这种情况下,您可以将 headerLeft 选项设置为将呈现的 React 元素 我知道问题涉及 goBack( ) headerRight 组件的函数。

我想用诸如 navigation.navigate("previousScreen",{{..props}}) 之类的内容覆盖与 headerLeft 后退按钮相关的默认函数 goBack() 。

而且(这非常重要!!)我想在特定屏幕本地使用此行为,而不是全局。

我尝试过类似的事情但不起作用。

 export default function App(){
 return(
 <NavigationContainer>
  <Stack.Navigator>
    <Stack.Screen name="FirstScreen" component={FirstScreen}/>
    <Stack.Screen name="SecondScreen" component={SecondScreen} options={{headerLeft: () => (
        <HeaderBackButton
          onPress={() =>navigation.navigate("FirstScreen",{//stuff//})}
          title="Info"
          color="#fff"
        />
      ),}}/>
  </Stack.Navigator>
</NavigationContainer>
 )}
Run Code Online (Sandbox Code Playgroud)

Est*_*ban 5

对于react-navigation v6,您可以在useEffect中使用setOptions

import { HeaderBackButton } from '@react-navigation/elements';

...

const MyScreen = ({navigation}) => {

     useEffect( () => {
            navigation.setOptions({ headerShown: true,
                                    headerLeft: (props) => (
                                        <HeaderBackButton
                                            {...props}
                                            onPress={() => {
                                                navigation.navigate('MyOtherScreen');
                                            }}
                                        />
                                    )
                                  });
        } ); 
}
Run Code Online (Sandbox Code Playgroud)


dbl*_*ski 0

组件挂载时,注册后退按钮按下监听器

componentDidMount() {
    BackHandler.addEventListener('hardwareBackPress', this.onBackButtonPressAndroid)
}

componentWillUnmount() {
    BackHandler.removeEventListener('hardwareBackPress', this.onBackButtonPressAndroid)
}
Run Code Online (Sandbox Code Playgroud)

然后在函数中,您可以检查并处理操作,例如:

onBackButtonPressAndroid = () => {
    // Check if the current screen is focused or a subscreen is perhaps
    if (this.props.navigation.isFocused()) {
        if (someCondition) {
            // Do a navigation to a custom screen, pass props here if needed
            this.props.navigation.navigate('search')
            return true
            // Return true if you want to tell react navigation you've handled the back press
        }
        else if (this.state.offsetTop > 10) {
            // Ex. for scrolling to top
            this.scrollToTop()
            this.setState({
                offsetTop: 0,
            })
            return true
        }
    }
    // Return false if you want to tell react navigation you didn't handle the back press
    return false
}
Run Code Online (Sandbox Code Playgroud)

  • 我指的是标题后退按钮,而不是硬件按钮!谢谢 (2认同)