将组件存储到变量中并重用它

时间:2016-08-22 09:18:17

标签: reactjs react-native

好的,我把组件导入为

import Payment from './pages/payment';
import Chat from './pages/chat';

现在我正在使用Drawer组件并将其与Navigator一起使用,我的renderScene就变成了这样的

if( route.id == 'payment'){
    return  <Drawer  xx={} yy={} and a lot more >
              <Payment navigator={navigator} />
            </Drawer>
}

if(route.id == 'chat'){
    return <Drawer  xx={} yy={} and a lot more >
              <Chat navigator={navigator} />
            </Drawer>
}

这些冗长的Drawer代码被反复使用。我想将<Payment navigator={navigator} >或其他内容存储到变量中,然后仅使用Drawer返回一次。

我如何存储并使用抽屉返回?

由于

2 个答案:

答案 0 :(得分:2)

不确定你是否在问这个问题,但是如下:

const routes = {
 payment: Payment,
 chat: Chat
 ...
}

然后,只是:

const Scene = routes[route.id];
return (
  <Drawer  xx={} yy={} and a lot more >
    {<Scene navigator={navigator}/>}
  </Drawer>
)

答案 1 :(得分:0)

这里有3个选项:

// 1. Group the drawer props in an object
const drawerProps = {
  xx: ...,
  yy: ...
};
<Drawer {...drawerProps}>
  <Chat navigator={navigator} />    
</Drawer>

// 2. Define a wrapper object that populates the common Drawer props
const CustomDrawer = ({ children }) => (
  <Drawer  xx={} yy={} and a lot more>
    {children}
  </Drawer>
);


// 3. Define a wrapper object that populates the common Drawer props with default props. (Can be 
// overriden.)
const CustomDrawer = ({ 
  xx='XX',
  yy='YY',
  children 
}) => (
  <Drawer  xx={xx} yy={yy} and a lot more>
    {children}
  </Drawer>
);

编辑:我很想念您的问题,因为存储内部部分,您只需将其分配给变量并使用它。

const routes = {
  chat: <Chat navigator={navigator} />,
  payment: <Payment navigator={navigator} />,  
}


<Drawer {...drawerProps}>
  { routes[route.id] }
</Drawer>