在 React Navigation 中将道具传递给自定义抽屉导航器 [英] Passing props to Custom Drawer Navigator in React Navigation

查看:36
本文介绍了在 React Navigation 中将道具传递给自定义抽屉导航器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在反应导航抽屉菜单中.我想显示用户名John Doe",它处于我的主要组件 'Router' 如何将它传递给 CustomDrawerContentComponent.

In react navigation drawermenu. I want to display the username 'John Doe' which is in the state of my main component 'Router' How can I pass it the CustomDrawerContentComponent.

额外信息:我从 AsyncStorage 中获得这个名称组件DidMount

Extra Info: I'm getting this name from AsyncStorage in componentDidMount

这是我的代码

export default class Router extends Component {
  constructor(props) {
    super(props);
    this.state = {
      employeeName: "John Doe" //<-----How to pass this name to CustomDrawerContentComponent????
    };
  }

  render() {
    return <MyApp />;
  }
}

const MyApp = DrawerNavigator(
  {
    Home: {
      screen: Home
    },
    History: {
      screen: History
    },
    AddDetails: {
      screen: AddDetails
    }
  },
  {
    initialRouteName: "Home",
    drawerPosition: "left",
    contentComponent: CustomDrawerContentComponent,
    drawerOpenRoute: "DrawerOpen",
    drawerCloseRoute: "DrawerClose",
    drawerToggleRoute: "DrawerToggle",
    contentOptions: {
      activeTintColor: "#EF4036"
    }
  }
);

const CustomDrawerContentComponent = props => (
  <Container>
    <Header style={styles.drawerHeader}>
      <Body style={styles.container}>
        <Image
          style={styles.drawerImage}
          source={{
            uri: "http://themes.themewaves.com/nuzi/wp-content/uploads/sites/4/2013/05/Team-Member-3.jpg"
          }}
        />
        <Text style={styles.drawerText}>**How get the name here?**</Text>
      </Body>
    </Header>

    <Content>
      <DrawerItems {...props} />
    </Content>
  </Container>
);

推荐答案

你可以使用 screenProps:

You can use screenProps:

<MyApp
  screenProps={{employeeName: this.state.employeeName}}
/>

然后在您的自定义内容组件中使用它:

And then use it in your custom contentComponent:

contentComponent:(props)=>(
  <View>
    <Text>{props.screenProps.employeeName}</Text>
    <DrawerItems {...props} />
  </View>
)

这是您问题的答案.但首先,我不建议将您的顶级组件用于此类业务逻辑.仅用于导航.

This is the answer for your question. But first of all I don't recommend using your top level component for such business logic. Use it only for navigation.

在这里看到我的答案:自定义抽屉

我建议您按照我在回答中的描述创建一个 Redux 连接的自定义抽屉.如果您不知道如何使用 Redux,我绝对建议您学习它.随着应用程序的增长,您将需要它.

I recommend you to create a Redux connected custom drawer as I describe in my answer. If you don't know how to use Redux, I definitely recommend you to learn it. You will need it as your application grows.

这篇关于在 React Navigation 中将道具传递给自定义抽屉导航器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆