在React Navigation中将道具传递到Custom Drawer Navigator

时间:2018-07-29 13:30:24

标签: javascript react-native react-navigation

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

  

其他信息:我从AsyncStorage中获得此名称   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>
);

2 个答案:

答案 0 :(得分:3)

您可以使用screenProps:

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

然后在自定义contentComponent中使用它:

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

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

在这里查看我的答案:Customizing Drawer

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

答案 1 :(得分:2)

只需作为屏幕道具

Render(){
return <Myapp screenprops={employeename:this.state.employeeName}/>;
}

您可以像这样this.props.screenprops.employeename从抽屉中访问它