从React Navigation v4升级到v5时获取默认样式

 收藏

I am currently using React Navigation v4 and migrating to v5. I am using the official documentation for the upgrade but unfortunately, I encountered a blocker.

在V4中,我可以执行以下操作:

export default function ExampleScreen(props) {
  return <View></View>
}

ExampleScreen.navigationOptions = ({navigation, navigationOptions}) => ({
  headerStyle: {
    ...navigationOptions.headerStyle,
    borderBottomWidth: 0
  },
  headerRight: () => <SearchBox navigation={navigation} />
})

But in V5 I can't seem to access the navigationOptions parameter so I can't get the navigationOptions.headerStyle.

export default function ExampleScreen(props) {
  props.navigation.setOptions({
    headerStyle: {
      // I can't get the default styles here.
      borderBottomWidth: 0
    },
    headerRight: () => <SearchBox navigation={props.navigation} />
  })

  return <View></View>
}

我该如何在React Navigation V5中做到这一点,因为它在其他任何地方都没有记录?

回复
  • ksit 回复

    将默认值放入变量并导出。然后在需要的地方导入并使用:

    export const headerStyle = {
      /* whatever */
    };
    
    // Use in `screenOptions`
    <Stack.Navigator screenOptions={{ headerStyle }}></Stack.Navigator>;
    
    // Use in `setOptions`
    navigation.setOptions({
      headerStyle: [headerStyle, { borderBottomWidth: 0 }],
      headerRight: () => <SearchBox navigation={props.navigation} />
    });