问题
I have made a custom component for header title(stack navigator)which shows user name along with some image. On this page I have to edit the username and on success Update it in header as well
So my question is How to change/update title dynamically?
回答1:
This can be done using the navigation props.
You can use this.props.navigation.state.params
in a component to set a new property. Call:
navigation.setParams({ param: value })
See the documentation on headers for more detail.
回答2:
the code that shows in the part below is for the version of react-navigation 2.x
you can try the following:
in my case I have the configuration of navigation in a file called, app-navigator.js
const ChatStackNavigator = createStackNavigator(
{
People: ListPeopleScreen, // People Screen,
Screen2: Screen2
},
{
initialRouteName: 'People'
navigationOptions: ({navigation}) => ({
header: <AppBar title={navigation.getParam('appBar', {title: ''}).title}/>
}),
cardStyle: {
backgroundColor: 'white'
}
}
);
The screen file would be as follows:
import React, {Component} from 'react';
import {connect} from 'react-redux';
import {List, ListItem} from 'react-native-elements';
class ListPeopleScreen extends Component {
list = [
{
name: 'Amy Farha',
avatar_url: 'https://s3.amazonaws.com/uifaces/faces/twitter/ladylexy/128.jpg',
subtitle: 'Vice President'
},
{
name: 'Chris Jackson',
avatar_url: 'https://s3.amazonaws.com/uifaces/faces/twitter/adhamdannaway/128.jpg',
subtitle: 'Vice Chairman'
}
];
componentDidMount() {
this.props.navigation.setParams({
appBar: {
title: 'Clientes'
}
});
}
render() {
return <List
containerStyle={{marginBottom: 30}}
>
{
this.list.map((item) => (
<ListItem
roundAvatar
avatar={{uri: item.avatar_url}}
key={item.name}
title={item.name}
/>
))
}
</List>
};
}
export default connect(null)(ListPeopleScreen);
NOTE: in my case I am using redux, and the library of components react-native-elements
回答3:
You can simply change the header by using the method shown in the code below, or the one in the original documentation: React Navigation - using params in the title
static navigationOptions = ({ navigation }) => {
const edit = navigation.getParam('edit', false);
if(edit){
return {
headerTitle: 'Edit Page',
};
}else{
return {
headerTitle: 'Normal Page',
};
}
};
来源:https://stackoverflow.com/questions/46200454/react-native-dynamically-update-header-title-in-stack-navigator