导航器外的导航不起作用
navigation outside the navigator not working
我正在熟悉新的 react-navigation 版本。我在使用 navigation.navigate 方法时遇到问题。
当前行为
当我们点击菜单按钮时,它抛出一个错误 -
设备:(65:24) undefined 不是对象(正在评估 'navigation.navigate')
预期行为
点击菜单按钮,它应该打开抽屉
如何重现
虽然 FooterComponent
在 NavigationContainer 内呈现,但它不是屏幕或在任何导航器内,因此它不会有可用的导航上下文,也无法从 useNavigation
.
但是,对于这个特定问题有一个解决方法,您可以在其中为 NavigationContainer 创建一个 ref 并将该 ref 传递给 FooterComponent。这在 the "Navigating without navigation prop" section of React Navigation docs 中有详细描述。应用于您的零食,需要进行以下更改(加上相关的导入):
const Navigator = () => {
const navigationRef = useRef();
return (
{...}
<NavigationContainer ref={navigationRef}>
{...}
<FooterComponent navigationRef={navigationRef} />
const FooterComponent = ({ navigationRef }) => {
{...}
<TouchableOpacity onPress={() => navigationRef.current.dispatch(DrawerActions.openDrawer())
}>
然后您可以对其他选项卡使用 navigationRef.current.navigate('Notifications')
或 navigationRef.current.navigate('Home')
的相同方法。
您可以在此处看到这适用于您的零食:https://snack.expo.io/POeoVzAsG
我正在熟悉新的 react-navigation 版本。我在使用 navigation.navigate 方法时遇到问题。
当前行为
当我们点击菜单按钮时,它抛出一个错误 - 设备:(65:24) undefined 不是对象(正在评估 'navigation.navigate') 预期行为
点击菜单按钮,它应该打开抽屉 如何重现
虽然 FooterComponent
在 NavigationContainer 内呈现,但它不是屏幕或在任何导航器内,因此它不会有可用的导航上下文,也无法从 useNavigation
.
但是,对于这个特定问题有一个解决方法,您可以在其中为 NavigationContainer 创建一个 ref 并将该 ref 传递给 FooterComponent。这在 the "Navigating without navigation prop" section of React Navigation docs 中有详细描述。应用于您的零食,需要进行以下更改(加上相关的导入):
const Navigator = () => {
const navigationRef = useRef();
return (
{...}
<NavigationContainer ref={navigationRef}>
{...}
<FooterComponent navigationRef={navigationRef} />
const FooterComponent = ({ navigationRef }) => {
{...}
<TouchableOpacity onPress={() => navigationRef.current.dispatch(DrawerActions.openDrawer())
}>
然后您可以对其他选项卡使用 navigationRef.current.navigate('Notifications')
或 navigationRef.current.navigate('Home')
的相同方法。
您可以在此处看到这适用于您的零食:https://snack.expo.io/POeoVzAsG