将Props传递到React Native BottomNavigation场景

bvuwiixz  于 2023-03-31  发布在  React
关注(0)|答案(2)|浏览(126)

我有一个用户配置文件管理页面底部导航.类似于原始的例子:

import React from 'react';
import { BottomNavigation } from 'react-native-paper';

// Components
import CodeScanner from '../../../screens/vendors/CodeScannerScreen';
import Home from '../../../screens/home/HomeScreen';
import Vendors from '../vendors/VendorsStack';
   
// Routes
const homeRoute = () => <Home />;
const socialRoute = () => <Social />;
const friendsRoute = () => <Friends />;

const HomeTabs = (props) => {
   
   const [index, setIndex] = React.useState(0);
   const [user, setUser] = React.useState()

   useEffect(()=>{
       // here we load user data from remote server and set it in the user 
       setUser(remoteUserInfo)
   }, [])

   const [routes] = React.useState([
      { key: 'home', title: 'Home', icon: 'home' },
      { key: 'social', title: 'Social', icon: 'social' },
      { key: 'friends', title: 'Friends', icon: 'friends' }
   ]);
   
   const renderScene = BottomNavigation.SceneMap({
      home: homeRoute,
      social: socialRoute,
      friends: friendsRoute
   });

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

export default HomeTabs;

由于我在HomeTabs组件中有用户信息,并且它会在每个场景中使用,因此我希望有一种方法来传递它(通常通过 prop )。但我找不到任何方法来这样做。我试过:

const homeRoute = ({user}) => <Home user={user} />;

const renderScene = BottomNavigation.SceneMap({
          home: <homeRoute user={user}/>,
          social: <socialRoute user={user}/>,
          friends: <friendsRoute user={user}/>
       });

但这不起作用。有什么建议吗?我想远离复杂的解决方案(例如Redux或Context)。

uurv41yg

uurv41yg1#

如果你要传递 prop ,你应该声明你的路由如下

const homeRoute = (props) => <Home {...props}/>;
yrdbyhpb

yrdbyhpb2#

我也遇到了同样的问题,用typescript解决了这个问题:

type UserProps={user: User|undefined};

type NavProps = {
  route: {key: string};
  jumpTo: (key: string) => void;
};

function HomeView(props:UserProps&NavProps) {
    const user=props.user;
    const setUser=props.setUser;
    const route=props.route;
    const jumpTo=props.jumpTo;
}

const HomeSceen = (props:NavProps) => <HomeView {...props}  user={user} />;

const renderScene = BottomNavigation.SceneMap({
    home: HomeSceen,
  });

相关问题