【问题标题】:How to make custom useTabDoublePressEffect() in React Navigation?如何在 React Navigation 中自定义 useTabDoublePressEffect()?
【发布时间】:2022-08-14 03:02:35
【问题描述】:

当我按下 Tab.Navigator 中已选择的选项卡时,如何调用回调函数?

    标签: react-native react-navigation


    【解决方案1】:

    自定义 useTabDoublePressEffect 钩子:

    import {EventArg, useNavigation, useRoute} from '@react-navigation/native';
    import React from 'react';
    
    export default function useTabDoublePressEffect(callback: Function) {
      const navigation = useNavigation();
      const route = useRoute();
    
      React.useEffect(() => {
        let current = navigation; // The screen might be inside another navigator such as stack nested in tabs
    
        // We need to find the closest tab navigator and add the listener there
        while (current && current.getState().type !== 'tab') {
          current = current.getParent();
        }
    
        if (!current) {
          return;
        }
    
        const unsubscribe = current.addListener(
          // We don't wanna import tab types here to avoid extra deps
          // in addition, there are multiple tab implementations
          //   @ts-expect-error
          'tabPress',
    
          (e: EventArg<'tabPress', true>) => {
            // We should scroll to top only when the screen is focused
            const isFocused = navigation.isFocused(); // In a nested stack navigator, tab press resets the stack to first screen
            // So we should scroll to top only when we are on first screen
    
            const isFirst =
              navigation === current ||
              navigation.getState().routes[0].key === route.key;
    
            // Run the operation in the next frame so we're sure all listeners have been run
            // This is necessary to know if preventDefault() has been called
    
            requestAnimationFrame(() => {
              if (isFocused && isFirst && !e.defaultPrevented) {
                callback();
              }
            });
          },
        );
        return unsubscribe;
      }, [navigation, route.key]);
    }
    
    

    如何使用它的基本示例:

    import React, {useState} from 'react';
    import {Text} from 'react-native';
    import useTabDoublePressEffect from '../hooks/useTabDoublePressEffect';
    
    export default function SomeComponent() {
      const [text, setText] = useState('Hello');
    
      useTabDoublePressEffect(() => setText('Bye'));
    
      return <Text>{text}</Text>;
    }
    

    代码借鉴自:

    https://github.com/react-navigation/react-navigation/blob/ac24e617af10c48b161d1aaa7dfc8c1c1218a3cd/packages/native/src/useScrollToTop.tsx

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-25
      • 1970-01-01
      • 2018-10-24
      • 1970-01-01
      • 1970-01-01
      • 2017-11-30
      • 2021-07-31
      • 1970-01-01
      相关资源
      最近更新 更多