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

In my react-native 0.62 app, I created an <AppHeader /> component to render the header so that I don't have to repeat the same code in every screen.

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

enter image description here

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

I'm using native-base so the header understands <Left> and <Right>.

My question is how would I pass a component to my <AppHeader /> and what would the conditional part look like?

Here's my <AppHeader /> component now:

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;
评论
gvel
gvel

React组件可以像其他任何变量值一样使用。

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