【问题标题】:React native navigation v5 tab press not working反应本机导航 v5 选项卡按下不起作用
【发布时间】:2020-06-29 18:00:26
【问题描述】:

从代码中可以看出,tabPress 没有被调用,是我做错了还是我遗漏了什么,不幸的是我没有找到任何反应导航版本 5 的代码示例。

<Tab.Navigator labeled={false} barStyle={{backgroundColor: '#ffffff', height: 55}} options={{
        tabPress: ({navigation}) => {
            console.log('nav tab press triggered')
        }
    }}>
        <Tab.Screen name={`DeviceNavigatorTab`} component={DeviceNavigator} options={{
            tabBarIcon: ({tintColor}) => <Image source={require('../../images/feather_home-menu.png')}
                                                style={{width: 26, height: 26, tintColor}}/>,
            tabPress: ({navigation}) => {
                console.log('tab press triggered')
            }
        }} tabPress={() => { console.log('prop tab pressed') }}/>
        <Tab.Screen name={`AlarmNavigatorTab`} component={AlarmNavigator} options={{
            tabBarIcon: ({tintColor}) => <Image source={require('../../images/feather_alert-circle.png')}
                                                style={{width: 26, height: 26, tintColor}}/>,
        }}/>
        <Tab.Screen name={`ProfileNavigatorTab`} component={ProfileNavigator} options={{
            tabBarIcon: ({tintColor}) => <Image source={require('../../images/feather_user.png')}
                                                style={{width: 26, height: 26, tintColor}}/>,
        }} />
    </Tab.Navigator>

【问题讨论】:

标签: react-native react-navigation-v5 react-navigation-bottom-tab


【解决方案1】:

我在文档中发现了一些我以前从未见过的新东西,这是将监听器添加到屏幕的方式,每次用户单击选项卡时,它都会转到此选项卡内的第一个堆栈屏幕

https://reactnavigation.org/docs/navigation-events/#listeners-prop-on-screen

<Tab.Screen 
  name="DeviceNavigatorTab" 
  component={DeviceNavigator} 
  listeners={({ navigation, route }) => ({
    tabPress: e => {
      if (route.state && route.state.routeNames.length > 0) {
          navigation.navigate('Device')
      }
    },
  })}
/>

【讨论】:

【解决方案2】:

您需要在组件中收听/订阅“tabPress”事件,如下所示。

React.useEffect(() => {
  const unsubscribe = navigation.addListener('tabPress', e => {
    // Prevent default behavior
    e.preventDefault();

    // Do something manually
    // ...
  });

  return unsubscribe;
}, [navigation]);

【讨论】:

  • 文档中的这个例子不起作用。未调用侦听器。
  • 出于好奇,有没有人解决这个问题?
  • 为了让它工作,它需要在一个组件中作为 Tab.Screen 的子组件
  • 如果您的 TabNavigator 已嵌套 StackNavigators,并且您正试图从嵌套堆栈中的屏幕监听 tabPress 事件,您可能会忘记调用 navigation.getParent()(反应导航 6)。 getParent() 在反应导航 5 中以前是 dangerouslyGetParent()
猜你喜欢
  • 1970-01-01
  • 2020-07-10
  • 1970-01-01
  • 2020-04-19
  • 1970-01-01
  • 2020-12-13
  • 2021-09-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多