如何禁用特定Tab.Screen的滚动

问题描述 投票:0回答:1

我正在使用 React Native 和 TypeScript。我正在尝试创建一个顶部选项卡栏并使用权限。当某人无权访问某个选项卡时,该选项卡将被禁用。我已经设法更改其样式并防止单击它(使用

e.preventDefault()
),但我想防止其他选项卡滚动到它。

我尝试使用

swipeEnabled: false
,但它允许我从另一个选项卡滚动到禁用的选项卡,并阻止从禁用的选项卡滚动到另一个选项卡。我特别想做相反的事情:防止用户从活动选项卡滚动到禁用选项卡。

这是我的代码(禁用选项卡):

        <Tab.Screen
          listeners={{
            tabPress: e => {
              e.preventDefault();
            },
          }}
            options={{
              tabBarActiveTintColor: Colors.buttonDisabled,
              tabBarInactiveTintColor: Colors.buttonDisabled,
              tabBarLabel: () => (
                <Subtitle variant='subtitle3' style={{ color: Colors.buttonDisabled }}>
                  {e.props.name}
                </Subtitle>
              )
            }}
            {...e.props}
            component={Forbidden}
          ></Tab.Screen>

我的 TopTab 组件:

javascript typescript react-native layout react-tabs
1个回答
0
投票

我能想到实现所需行为的一种方法是分别使用

state
navigation
钩子中的
useNavigationState
useNavigation
对象。我们可以确定禁用选项卡的
index
,并通过监听
state
的更改并在用户到达禁用选项卡时导航回上一个选项卡来阻止用户滚动到该选项卡。示例代码如下:

import { useNavigationState, useNavigation } from '@react-navigation/native';
// ...rest
const navigation = useNavigation();
const state = useNavigationState(state => state);
const disabledTabIndex = 1; // <--- Replace this with the index of the disabled tab

useEffect(() => {
  if (state.index === disabledTabIndex) {
    const previousIndex = state.index - 1;
    if (previousIndex >= 0) {
      navigation.navigate(state.routeNames[previousIndex]);
    }
  }
}, [state, navigation]);
© www.soinside.com 2019 - 2024. All rights reserved.