react navigation v3 set screenProps through AppContainer

微笑、不失礼 提交于 2019-12-23 01:49:05

问题


I need to pass theme settings to navigation options of each screen. Settings are stored in redux. In old version I would write something like that:

const AppNavigator = StackNavigator({
  Home: { screen: MainList },
  Settings: { screen: Settings },
  NewEvent: { screen: NewEvent },
  Contacts: { screen: Contacts },
  Map: { screen: Map},
})

And in render function...

<AppNavigator 
   screenProps={{
     settings: this.props.settings,
     headerTintColor: '#ffffff'
   }}
/>

...where props.settings is a part of redux state. Wich is used inside navigationOptions

static navigationOptions = ({ navigation, screenProps }) => {
  let settings = screenProps.settings;
  let theme = settings? settings.theme: null;

  return {
    title: strings.account,
    headerTintColor: screenProps.headerTintColor,
    headerStyle: {backgroundColor: theme? theme.def.primaryColor: null}
  };
};

But how should I do this now when I must wrap my Navigators with createAppContainer? Using navigation.setParams makes a visible delay in emulator so its not a proper solution for me... Keep in mind theme can be changed at any time!


回答1:


Well) Turnsout you can achive that by creating a custom navigator like this:

class NavWrapper extends Component {
  static router = AppNavigator.router;
  render() {
    const { navigation } = this.props;

    return <AppNavigator
      navigation={navigation}
      screenProps={{
        settings: this.props.settings,
        headerTintColor: '#ffffff'
      }}
    />;
  }
}

const AppNavWrapper = connect(state => ({settings: state.settings}))(NavWrapper);
const AppContainer = createAppContainer(AppNavWrapper);

And then in your root component

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

Hope that helps :)



来源:https://stackoverflow.com/questions/53377536/react-navigation-v3-set-screenprops-through-appcontainer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!