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

React Native Paper底部导航跳转问题:navigation未定义

React Native Paper Bottom Navigation页面跳转问题解决

问题核心原因

  1. React Native Paper的BottomNavigation是标签页切换组件,不会自动向子页面传递navigation和route对象,所以你在MusicRoute中获取的navigation会是undefined。
  2. 代码存在两处语法错误:
    • TouchableOpacity的onPress错误使用了双层大包裹,应为onPress={switchToAlbum}而非onPress={{swichToAlbum}}
    • 函数名拼写错误:swichToAlbum → switchToAlbum

解决方案

BottomNavigation通过控制index状态切换活跃页面,我们需要将切换逻辑通过props传递给子组件,具体修改如下:

修正后的完整代码

import * as React from 'react';
import { View, TouchableOpacity } from 'react-native';
import { BottomNavigation, Text } from 'react-native-paper';

const CenterView = ({children}) => {  
  return (
    <View style={{ 
      height: '100%', 
      flexDirection: 'column',
      justifyContent: 'center', 
      alignItems: 'center' 
    }}>
      {children}
    </View>
  )
}

const MusicRoute = ({switchToAlbum}) => {
  return (
    <CenterView>
      <Text>Music</Text>
      <TouchableOpacity onPress={switchToAlbum}>
        <Text>Go to Album screen</Text>
      </TouchableOpacity>
    </CenterView>
  )
}

const AlbumsRoute = () => <CenterView><Text>Albums</Text></CenterView>;
const RecentsRoute = () => <CenterView><Text>Recents</Text></CenterView>;
const NotificationsRoute = () => <CenterView><Text>Notifications</Text></CenterView>;

const App = () => {
  const [index, setIndex] = React.useState(0);
  const [routes] = React.useState([
    { key: 'music', title: 'Music', focusedIcon: 'heart', unfocusedIcon: 'heart-outline'},
    { key: 'albums', title: 'Albums', focusedIcon: 'album' },
    { key: 'recents', title: 'Recents', focusedIcon: 'history' },
    { key: 'notifications', title: 'Notifications', focusedIcon: 'bell', unfocusedIcon: 'bell-outline' },
  ]);

  // 自定义renderScene,传递切换方法给目标页面
  const renderScene = ({ route }) => {
    switch (route.key) {
      case 'music':
        return <MusicRoute switchToAlbum={() => setIndex(1)} />;
      case 'albums':
        return <AlbumsRoute />;
      case 'recents':
        return <RecentsRoute />;
      case 'notifications':
        return <NotificationsRoute />;
      default:
        return null;
    }
  };

  return (
    <BottomNavigation
      navigationState={{ index, routes }}
      onIndexChange={setIndex}
      renderScene={renderScene}
      shifting={false}
    />
  );
};

export default App;

修改说明

  • 替换BottomNavigation.SceneMap为自定义renderScene函数,实现向MusicRoute传递切换方法
  • switchToAlbum方法通过setIndex(1)直接切换到albums页面(对应routes数组的第2个元素,索引为1)
  • 修复了onPress语法错误和函数名拼写问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 23:23:14