使用 React Navigation 设置样式 Header(从 V3 到 V5)

Styling Header with React Navigation(From V3 to V5)

所以我和 this tutorial 一起尝试制作一个具有原生反应的应用程序,它使用 react-navigation 的 v3,但我正在尝试使用 v5。问题在于,以前在旧版本中使用的样式不再适用。

**// setup of navigator**
const Stack = createStackNavigator();

const Travel = () => {
  return (
    <Stack.Navigator initialRouteName="List">
      <Stack.Screen name="Article" component={Article} />
      <Stack.Screen
        name="List"
        component={List}
        options={{
          title: null,
        }}
      />
    </Stack.Navigator>
  );
};

**// screen in question - List**
const styles = StyleSheet.create({
  flex: {
    flex: 1,
  },
  row: {
    flexDirection: 'row',
  },
  header: {
    backgroundColor: 'orange',
  },
});

export default class List extends React.Component {
  static navigationOptions = {
    header: (
      <View style={[styles.flex, styles.row, styles.header]}> **// styles won't get applied for some reason**
        <View>
          <Text>Search for a place</Text>
          <Text>Destination</Text>
        </View>
        <View>
          <Text>Avatars</Text>
        </View>
      </View>
    ),
  };

  render() {
    return <Text>List</Text>;
  }
}

我不知所措,无法完成这项工作,看起来像这样:goal navigation 知道如何将此代码从本教程中的 v3 版本更新到 react-navigation 的 v5 支持版本吗?

更新: 通过这段代码,我离目标更近了:

import React from 'react';
import { createStackNavigator } from '@react-navigation/stack';
import { Text, View } from 'react-native';
import Article from '../screens/Article';
import { List } from '../screens/List';

const Stack = createStackNavigator();

const ListHead = () => {
  return (
    <View
      style={{
        flex: 1,
        flexDirection: 'row',
        justifyContent: 'space-around',
        backgroundColor: 'orange',
      }}
    >
      <View>
        <Text>Search for a place</Text>
        <Text>Destination</Text>
      </View>
      <View>
        <Text>Avatars</Text>
      </View>
    </View>
  );
};

const Travel = () => {
  return (
    <Stack.Navigator initialRouteName="List">
      <Stack.Screen name="Article" component={Article} />
      <Stack.Screen
        name="List"
        component={List}
        options={{
          headerTitle: () => <ListHead />,
        }}
      />
    </Stack.Navigator>
  );
};

export default Travel;

但是我无法让它们像目标照片那样适当地间隔开,而且它们没有占据整个宽度。

在 react-navigation v5 中,您可以使用 headerLeftheaderRight像这样自定义导航 header。您也可以根据需要指定样式。

这里是代码示例

export default class List extends React.Component {
  static navigationOptions = {
    headerLeft: () => (
      <View>
        <Text>Search for a place</Text>
        <Text>Destination</Text>
      </View>
    ),
    headerRight: () => (
      <View>
        <Text>Avatars</Text>
      </View>
    ),
    // you can specify your styles here also
    headerStyle: {},
    headerRightContainerStyle: {},
    headerLeftContainerStyle: {},
  };

  render() {
    return <Text>List</Text>;
  }
}

希望对您有所帮助!