react-navigation dynamic header doesn't work?

99封情书 提交于 2019-12-22 10:09:28

问题


I followed exactly the tutorial https://reactnavigation.org/docs/intro/ But the header does not show up. Here is the code and the result

import Expo from 'expo';
import React from 'react';
import { StyleSheet, Text, View, Button } from 'react-native';
import {StackNavigator} from 'react-navigation';


class HomeScreen extends React.Component {
  static navigationOptions = {
    title: 'Welcome',
  }

  render() {
    const {navigate} = this.props.navigation;
    return (
      <View style={styles.container}>
        <Text>Open up main.js to start working on your app!</Text>
        <Button onPress={()=>navigate('Chat',{user:'Lucy'})} title = 'Chat with Lucy'></Button>
      </View>
    );
  }
}
class ChatScreen extends React.Component {
  // Nav options can be defined as a function of the screen's props:
  static navigationOptions = ({ navigation }) => ({
    title: `Chat with ${navigation.state.params.user}`,
  });
  render() {
    // The screen's current route is passed in to `props.navigation.state`:
    const { params } = this.props.navigation.state;
    return (
      <View>
        <Text>Chat with {params.user}</Text>
      </View>
    );
  }
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});
const SimpleApp = StackNavigator({
  Home: {screen: HomeScreen},
  Chat: {screen: ChatScreen}
})
Expo.registerRootComponent(SimpleApp);

And here is the screen result when I click on the button

Another problem is that if I only use

static navigationOptions = {
    title: 'Chat with Lucy',
  };

Then, the "Welcome" is still next to the mark "<", which is different from the tutorial.


回答1:


You are using docs for a version newer than the version you have installed (similar issue on githib). It's about difference between npm and github versions. Documents are for the github version, which is newer, but you installed react-navigation from npm.

The problem is you can't use navigationOptions as a function right now. When you do that it can't find navigationOptions, so there won't be a header. Use instead this:

static navigationOptions = {
  title: (navigation) => (`Chat with ${navigation.state.params.user}`),
};

When title exist, previous page title won't be shown left of the header.

Or update your package.json, so you can use the version of react-navigation docs:

"react-navigation": "git+https://github.com/react-community/react-navigation.git#7165efc",


来源:https://stackoverflow.com/questions/43485514/react-navigation-dynamic-header-doesnt-work

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