P粉7887656792023-08-18 14:54:31
What you want to do is more suited to a single page application architecture where you have a single main container that holds changing content based on navigation, however, React Navigation is designed for stacking screens and navigating between them of.
You can create a custom navigation component, let's call it NavigationContainer
, which holds the changing content. This component will manage the currently displayed page and render the content accordingly, similar to this:
const NavigationContainer = () => { const [currentPage, setCurrentPage] = useState('Home'); // 默认页面 const navigateTo = (page) => { setCurrentPage(page); }; const renderContent = () => { switch (currentPage) { case 'Home': return <HomeContent />; case 'Profile': return <ProfileContent />; // 添加更多不同页面的情况 default: return null; } }; return ( <View style={{ flex: 1 }}> <CustomNavBar navigateTo={navigateTo} /> {renderContent()} </View> ); }; export default NavigationContainer;
CustomNavBar
is another component that contains buttons or links for each page.
When the button/link is pressed it will call the navigateTo
function which is received as props from its parent component i.e. NavigationContainer
to update the currentPage# there ##state:
const CustomNavBar = ({ navigateTo }) => { return ( <View> <TouchableOpacity onPress={() => navigateTo('Home')}> <Text>Home</Text> </TouchableOpacity> <TouchableOpacity onPress={() => navigateTo('Profile')}> <Text>Profile</Text> </TouchableOpacity> // 添加更多按钮/链接以供其他页面使用 </View> ); }; export default CustomNavBar;limit
You may also lose some of the built-in navigation functionality provided by libraries like React Navigation.