本文介绍了react navigation v3 通过 AppContainer 设置 screenProps的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将主题设置传递给每个屏幕的导航选项.设置存储在 redux 中.在旧版本中,我会这样写:

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},
})

在渲染函数中...

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

...其中 props.settings 是 redux state 的一部分.在 navigationOptions 中使用 Wich

...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}
  };
};

但是当我必须用 createAppContainer 包装我的导航器时,我现在应该怎么做?使用 navigation.setParams 会在模拟器中造成明显的延迟,所以这对我来说不是一个合适的解决方案......请记住主题可以随时更改!

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!

推荐答案

好吧)结果你可以通过像这样创建自定义导航器来实现:

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);

然后在你的根组件中

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

希望有帮助:)

这篇关于react navigation v3 通过 AppContainer 设置 screenProps的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-15 05:42