在React Native中有条件地将子组件渲染到Header中

时间:2020-05-17 18:06:21

标签: reactjs react-native

在我的react-native 0.62应用程序中,我创建了一个<AppHeader />组件来呈现标题,这样就不必在每个屏幕上重复相同的代码。

标题和汉堡菜单是标准菜单,始终在其中,但是在某些屏幕上,我想在右侧区域添加一个,两个或多个按钮-见下文:

enter image description here

因此,最好在右侧接收和渲染组件。如果没有收到任何组件,那么我将不会渲染任何内容,并且右侧将为空白。

我正在使用native-base,因此标头可以理解<Left><Right>

我的问题是如何将组件传递给<AppHeader />,条件部分是什么样的?

现在是我的<AppHeader />组件:

import React from 'react';
import { Header, Left, Body, Right, Button, Icon, Title } from 'native-base';

// Stylesheet
import { styles } from './style-app-header';

const AppHeader = ({ navigation, title, rightSection }) => {

   return (
      <Header transparent>
         <Left style={{ flex: 1 }}>
            <Button transparent onPress={() => navigation.navigation.openDrawer()}>
               <Icon name="ios-menu" style={styles.icon} />
            </Button>
         </Left>
         <Body style={{ flex: 1 }}>
            <Title style={styles.title}>{title}</Title>
         </Body>
         {
            rightSection === null
            ? <Right />
            : <Right style={{ flex: 1 }}>
                  // How would I render the component here?
              </Right>
         }
      </Header>
   );
}

export default AppHeader;

1 个答案:

答案 0 :(得分:1)

可以像其他变量值一样使用反应组件。

const buttons = <button onClick={someAction}>Click me!</button>;
return (
    <AppHeader rightSection={buttons}/>
);
// ...
<Right style={{ flex: 1 }}>
    {rightSection}
</Right>
// ...