You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native中如何获取顶部Tab选中元素的ID?

解决React Native顶部Tab导航器仅获取选中项ID的问题

问题根源

你当前代码里的错误有两个:

  1. <TopTap.Screen> 组件并不支持 onPress 属性,你写的 onPress={setCat(element._id)} 会在组件渲染时直接执行 setCat 函数,导致所有Tab的ID都被调用,控制台输出所有结果。
  2. 没有正确监听Tab的切换事件来获取当前选中项的参数。

修复方案

以下是两种可行的修改方式:

方式一:使用导航器的 onTabPress 回调

直接在 TopTap.Navigator 中配置 screenOptions,通过 onTabPress 监听Tab点击事件,获取当前选中Tab的ID:

function MyTopTabs({navigation, route}) {
  const [product, setProduct] = React.useState();

  // 把setCat移到组件内部,方便调用
  const setCat = (id) => {
    axios.get(`https://localhost/api/get/parentCategory?id=${id}`)
    .then(response => {
      console.log(response)
    })
    .catch(error => {
      console.log(error);
    });
  };

  React.useLayoutEffect(() => {
    axios.get('https://localhost/api/get/category')
    .then(response => {
      setProduct(response.data)
    })
    .catch(error => {
      console.log(error);
    });
  }, []);

  return (
    <TopTap.Navigator 
      screenOptions={({ route }) => ({
        onTabPress: () => {
          // 从当前路由的initialParams中取出ID
          const tabId = route.params?.id;
          if (tabId) {
            setCat(tabId);
          }
        }
      })}
    >
      <TopTap.Screen  
        name="Product" 
        component={ProductScreen} 
        options={{tabBarLabel:'Products'}} 
      />
      {product && product.map(element => (
        <TopTap.Screen 
          key={element._id} 
          name={element.link} 
          initialParams={{ id: element._id }} 
          component={ProductList} 
          options={{ tabBarLabel: element.name }} 
        />
      ))}
    </TopTap.Navigator>
  );
}

方式二:监听导航状态变化

通过 navigation.addListener 监听路由状态变化,自动获取当前选中Tab的ID:

function MyTopTabs({navigation, route}) {
  const [product, setProduct] = React.useState();

  const setCat = (id) => {
    axios.get(`https://localhost/api/get/parentCategory?id=${id}`)
    .then(response => {
      console.log(response)
    })
    .catch(error => {
      console.log(error);
    });
  };

  React.useLayoutEffect(() => {
    axios.get('https://localhost/api/get/category')
    .then(response => {
      setProduct(response.data)
    })
    .catch(error => {
      console.log(error);
    });
  }, []);

  // 监听导航状态变化
  React.useEffect(() => {
    // 初始加载时获取当前路由ID
    const initialRoute = navigation.getCurrentRoute();
    const initialTabId = initialRoute?.params?.id;
    if (initialTabId) {
      setCat(initialTabId);
    }

    // 监听Tab切换事件
    const unsubscribe = navigation.addListener('state', () => {
      const currentRoute = navigation.getCurrentRoute();
      const currentTabId = currentRoute?.params?.id;
      if (currentTabId) {
        setCat(currentTabId);
      }
    });

    // 组件卸载时取消监听
    return unsubscribe;
  }, [navigation]);

  return (
    <TopTap.Navigator>
      <TopTap.Screen  
        name="Product" 
        component={ProductScreen} 
        options={{tabBarLabel:'Products'}} 
      />
      {product && product.map(element => (
        <TopTap.Screen 
          key={element._id} 
          name={element.link} 
          initialParams={{ id: element._id }} 
          component={ProductList} 
          options={{ tabBarLabel: element.name }} 
        />
      ))}
    </TopTap.Navigator>
  );
}

关键说明

  • 移除了原代码中 <TopTap.Screen> 上无效的 onPress 属性,避免渲染时批量执行函数。
  • 通过路由的 params 传递ID,再通过导航器的回调或状态监听获取当前选中项的参数,确保只调用选中Tab对应的接口。

内容的提问来源于stack exchange,提问作者Exciless_

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 01:54:25