如何在React Navigation中动态切换EmptyPage的头部标题组件
实现动态切换EmptyPage头部标题组件的方案
你可以通过路由参数传递+动态配置screen options的方式实现需求,具体步骤如下:
第一步:跳转时携带标识参数
在DiagnosticSearch页面跳转至EmptyPage时,通过navigation.navigate传递一个标识参数,用来区分来源页面:// DiagnosticSearch页面内的跳转代码 navigation.navigate('EmptyPage', { fromDiagnostic: true });第二步:动态配置EmptyPage的headerTitle
将原来固定的headerTitle改为函数形式,接收route参数,根据路由里的参数判断要渲染的头部组件:// 假设你有对应的DiagnosticSearchHeader组件 import DiagnosticSearchHeader from './DiagnosticSearchHeader'; <Stack.Screen name='EmptyPage' component={EmptyPage} options={({ route }) => ({ headerShown: true, headerTitle: () => { // 根据路由参数判断渲染哪个头部组件 if (route.params?.fromDiagnostic) { return <DiagnosticSearchHeader />; } // 默认渲染ProductSearch return <ProductSearch />; } })} />额外处理:参数重置(可选)
如果需要在离开EmptyPage后清除参数,避免下次进入时参数残留,可以在EmptyPage的useEffect里重置参数:import { useNavigation, useRoute } from '@react-navigation/native'; import { useEffect } from 'react'; function EmptyPage() { const navigation = useNavigation(); const route = useRoute(); useEffect(() => { return () => { // 页面卸载时重置参数 navigation.setParams({ fromDiagnostic: undefined }); }; }, [navigation]); // 页面其他逻辑... }
这样就能实现从DiagnosticSearch跳转过来时自动切换头部标题组件,其他场景默认使用ProductSearch。
内容的提问来源于stack exchange,提问作者Raghuram
相关产品推荐
相关产品推荐

