问题
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