Skip to content

导航与结果 ​

页面导航与传参 ​

jsx
function UserList() {
  const { navigation } = useModal();
  return <button onClick={() => navigation.navigate('UserDetail', { id: 8 })}>详情</button>;
}

function UserDetail() {
  const { navigation } = useModal();
  const { id } = useModalParams();
  return <>
    <p>用户 ID:{id}</p>
    <button onClick={() => navigation.setParams({ tab: 'settings' })}>切换标签</button>
    <button onClick={() => navigation.goBack({ updated: true })}>返回</button>
  </>;
}

navigate 进入路由,goBack(result?) 返回上一页,replace 替换当前页,reset 重置栈,setParams 合并当前页参数。隐藏页面 KeepAlive 保留状态;建议用 useFocusEffect 管理轮询和订阅。

页面跳转方法速查 ​

方法使用示例行为
navigatenavigation.navigate('UserDetail', { userId: 1 })跳转;已有同名页面则复用并截断后续页面
goBacknavigation.goBack({ saved: true })返回上一页并传回结果;根页面返回 false
replacenavigation.replace('Success', { id: 1 })替换当前页面
resetnavigation.reset('UserList')重置为新的根页面
setParamsnavigation.setParams({ tab: 'info' })浅合并当前页面参数
closeawait navigation.close({ id: 1 })关闭整个弹窗,不是返回上一页

navigation.canGoBack 判断能否返回;navigation.currentRoute 获取当前页面 { key, name, params };navigation.stack 获取完整导航栈。上一页使用 useNavigationResult(callback) 接收 goBack(result) 的结果,KeepAlive 页面使用 useIsFocused() / useFocusEffect() 管理焦点副作用。

完整签名见 类型声明。

Promise 结果与关闭守卫 ​

jsx
const { modal } = useModal();
const result = await modal.openAsync('editUser');
if (result.status === 'confirmed') console.log(result.value);
else console.log(result.status, result.reason);

弹窗内部:await navigation.close({ id: 1 }) 返回确认结果。modal.open() 返回 Promise<number | null>(弹窗实例 ID 或阻止打开时 null),不是 openAsync 的业务结果。

jsx
modalOptions: {
  onBeforeClose: async ({ reason }) => {
    if (hasUnsavedChanges()) return window.confirm('未保存,确定关闭吗?');
    return true;
  },
  onOpen: ctx => console.log('opened', ctx),
  onClose: ctx => console.log('closed', ctx.reason),
  onNavigate: ctx => console.log('navigated', ctx),
  onFocus: ctx => console.log('focused', ctx),
  onBlur: ctx => console.log('blurred', ctx),
}

关闭被拒绝时弹窗继续存在。替换、取消和 Provider 卸载等情况,openAsync() 返回不同状态与 reason。不要将 onClose 当作弹窗仍处于活动状态的回调。

打开时指定初始页面 ​

在同一个弹窗中注册多个页面,默认使用 initialRoute。通过 screen 可以在打开时覆盖初始页面,不需要先打开列表再导航。

jsx
const registry = {
  userModal: {
    initialRoute: 'UserList',
    screens: {
      UserList: { component: UserList, title: '用户列表' },
      UserDetail: { component: UserDetail, title: '用户详情' },
      UserEdit: { component: UserEdit, title: '编辑用户' },
    },
  },
};

modal.open({ name: 'userModal' }); // 打开 UserList
modal.open({
  name: 'userModal',
  screen: 'UserDetail',
  params: { userId: 1001 },
  placement: 'right',
  width: 600,
});

// Promise 和队列 API 也支持 screen
const result = await modal.openAsync({
  name: 'userModal',
  screen: 'UserEdit',
  params: { userId: 1001 },
});
  • screen 必须是 registry[name].screens 中注册的页面名称。
  • 省略 screen 时使用 initialRoute;params 始终传给选中的初始页面。
  • 请使用已注册的页面名称;打开失败时检查 Provider 的 onError 和状态。
  • 字符串调用 modal.open('userModal', params, options) 同样可用。
  • screen 只在打开时生效,打开后切换页面请使用 navigation.navigate()。

动态页面标题与路由参数 ​

每个弹窗页面均可通过 useModal() 取得 navigation.currentRoute,或者直接读取页面组件的 route 属性。params 是打开或跳转页面时传入的参数。

jsx
import { useEffect } from 'react';
import { useModal } from 'react-modal-navigation';

function UserDetail({ route }) {
  const { navigation } = useModal();
  const userId = route.params?.userId;

  useEffect(() => {
    navigation.setOptions({ title: `用户详情 #${userId}` });
  }, [navigation.setOptions, userId]);

  return <div>用户 ID:{userId}</div>;
}

// 打开时指定页面和参数
modal.open({ name: 'userModal', screen: 'UserDetail', params: { userId: 1001 } });

// 弹窗内导航时传参
navigation.navigate('UserDetail', { userId: 1002 });

navigation.setOptions(options) 更新当前路由实例的页面配置(例如 title、renderHeaderRight、showBackButton),不会修改 Registry,也不会重置页面栈。navigation.setParams({ userId: 1003 }) 则合并当前页面参数。详情见 完整类型声明。

栈操作与页面结果 ​

方法行为
push(name, params?)总是创建新路由实例,允许同名页面
pop(count?)返回指定层数,保留根页面
popTo(name)返回最近的同名页面
popToTop()返回根页面
navigateAsync(name, params?)等待目标页面返回结果
clearCache(name?)清理匹配的后台缓存
jsx
const navigation = useModalNavigation();
const result = await navigation.navigateAsync('SelectUser');
if (result.status === 'returned') {
  console.log(result.value);
}

目标页面调用 navigation.goBack(value) 返回。其他结果状态为 removed、cancelled、dismissed。导航操作应等待 Promise 返回的布尔值,判断是否成功。

页面专属参数与焦点 ​

jsx
const { userId } = useModalParams();
const route = useModalRoute();
const focused = useIsFocused();
useFocusEffect(useCallback(() => {
  const timer = setInterval(refresh, 5000);
  return () => clearInterval(timer);
}, [refresh]));
useNavigationResult(result => console.log(result));

后台页面应使用 useModalRoute 或 useModalParams 获取自己的参数,而不是当前活动路由的参数。

MIT License