通过AppContainer反应导航v3设置screenProps

时间:2018-11-19 15:11:09

标签: reactjs react-native redux react-navigation

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

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状态的一部分。 Wich用在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会在模拟器中产生明显的延迟,因此这对我来说不是一个正确的解决方案。请记住,可以随时更改主题!

1 个答案:

答案 0 :(得分:0)

嗯)事实证明,您可以通过创建这样的自定义导航器来实现这一目标:

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

然后在您的根组件中

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

希望有帮助:)