背面确认/警告对话框

Noi*_*art 5 react-native react-navigation

就像在网络浏览器中一样,我们有 onBeforeUnload (与 onUnload)来显示警报或一些警告“有未保存的数据 - 您确定要返回吗”。

我正在尝试做同样的事情。我在反应导航的文档中找不到任何内容。

我想做一些像这样的真正黑客的事情,但我不知道这是否是正确的方法:

import React, { Component } from 'react'
import { StackNavigator } from 'react-navigation'


export default function ConfirmBackStackNavigator(routes, options) {
    const StackNav = StackNavigator(routes, options);

    return class ConfirmBackStackNavigatorComponent extends Component {
        static router = StackNav.router;

        render() {
            const { state, goBack } = this.props.navigation;

            const nav = {
                ...this.props.navigation,
                goBack: () => {
                    showConfirmDialog()
                    .then(didConfirm => didConfirm && goBack(state.key))
                }
            };
            return ( <StackNav navigation = {nav} /> );
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

che*_*sam 6

React navigation 5.7 添加了对其的支持:

\n
function EditText({ navigation }) {\n  const [text, setText] = React.useState(\'\');\n  const hasUnsavedChanges = Boolean(text);\n\n  React.useEffect(\n    () =>\n      navigation.addListener(\'beforeRemove\', (e) => {\n        if (!hasUnsavedChanges) {\n          // If we don\'t have unsaved changes, then we don\'t need to do anything\n          return;\n        }\n\n        // Prevent default behavior of leaving the screen\n        e.preventDefault();\n\n        // Prompt the user before leaving the screen\n        Alert.alert(\n          \'Discard changes?\',\n          \'You have unsaved changes. Are you sure to discard them and leave the screen?\',\n          [\n            { text: "Don\'t leave", style: \'cancel\', onPress: () => {} },\n            {\n              text: \'Discard\',\n              style: \'destructive\',\n              // If the user confirmed, then we dispatch the action we blocked earlier\n              // This will continue the action that had triggered the removal of the screen\n              onPress: () => navigation.dispatch(e.data.action),\n            },\n          ]\n        );\n      }),\n    [navigation, hasUnsavedChanges]\n  );\n\n  return (\n    <TextInput\n      value={text}\n      placeholder="Type something\xe2\x80\xa6"\n      onChangeText={setText}\n    />\n  );\n}\n
Run Code Online (Sandbox Code Playgroud)\n

文档: https: //reactnavigation.org/docs/preventing-going-back

\n