This documentation is available as Markdown for AI agents and LLMs. See the full Markdown index or append .md to any documentation URL.

防止屏幕被移除

了解在 Expo Router 移除屏幕前如何确认导航。


使用 usePreventRemove() 可以在屏幕包含未保存的更改时保持它打开。当导航尝试移除屏幕时,这个钩子会运行你的回调。

🌐 Use usePreventRemove() to keep a screen open while it contains unsaved changes. The hook runs your callback when navigation tries to remove the screen.

src/app/edit-profile.tsx
import { usePreventRemove } from 'expo-router'; import { useState } from 'react'; import { Alert, Platform, TextInput } from 'react-native'; export default function EditProfile() { const [name, setName] = useState(''); const hasUnsavedChanges = name.length > 0; usePreventRemove(hasUnsavedChanges, ({ repeat }) => { const discardChanges = () => { setName(''); repeat(); }; if (Platform.OS === 'web') { if (window.confirm('Discard your unsaved changes?')) { discardChanges(); } return; } Alert.alert('Discard changes?', 'You have unsaved changes.', [ { text: 'Keep editing', style: 'cancel' }, { text: 'Discard', style: 'destructive', onPress: discardChanges, }, ]); }); return <TextInput value={name} onChangeText={setName} placeholder="Name" />; }

在调用 repeat() 之前,将传给 usePreventRemove() 的值设置为 false。这样可以让你的状态与防止移除保持同步。

🌐 Set the value passed to usePreventRemove() to false before calling repeat(). This keeps your state synchronized with removal prevention.

禁用删除保护

🌐 Disable removal prevention

这个 hook 还会返回一个函数,用来关闭阻止功能。当你想取消被阻止的操作并导航到其他地方时使用它。

🌐 The hook also returns a function that disables prevention. Use it when you want to cancel the blocked action and navigate somewhere else.

src/app/edit-profile.tsx
import { router, usePreventRemove } from 'expo-router'; import { useState } from 'react'; import { Button } from 'react-native'; export default function EditProfile() { const [hasUnsavedChanges, setHasUnsavedChanges] = useState(true); const disablePrevention = usePreventRemove(hasUnsavedChanges); function leaveForm() { setHasUnsavedChanges(false); disablePrevention(); router.replace('/profile'); } return <Button title="不保存直接离开" onPress={leaveForm} />; }

查看 Expo Router API 参考 了解所有防移除选项。

🌐 See the Expo Router API reference for all removal prevention options.