问题
I have created a component that connects to redux and returns the currently loaded item's
name as the navigation title.
But when I try to get the title from this component it breaks with this error:
Error: `title` cannot be defined as a function in navigation options for `StockScreen` screen.
Try replacing the following:
{
title: ({ state }) => state...
}
with:
({ navigation }) => ({
title: navigation.state...
})
This is my component:
import { connect } from 'react-redux';
let Title = () => {
if(this.props.item === null || this.props.item === undefined, this.props.item === {}) {
return '';
}else{
return this.props.item.TradeName;
}
}
const mapStateToProps = state => ({
item: state.stockItem.item,
});
export default ConnectedTitle = connect(mapStateToProps)(Title);
And this is how I have attempted to implement it within my react-navigation stack:
const Stack = createStackNavigator(
{
Home: {
screen: Tabs,
navigationOptions: {
header: null,
},
},
StockModal: {
screen: StockModal,
navigationOptions: {
header: null,
},
},
StockScreen: {
screen: StockScreen,
navigationOptions: {
headerRight: (<ConnectedSaveButton/>),
title: ConnectedTitle,
},
},
},
{}
);
回答1:
You are passing a React Component to the title in navigation options, while it should be a string. I think you need to use the headerTitle to achieve what you want
StockScreen: {
screen: StockScreen,
navigationOptions: {
headerRight: (<ConnectedSaveButton/>),
headerTitle: (<ConnectedTitle />),
},
}
From the documentation
title
String that can be used as a fallback for headerTitle. Additionally, will be used as a fallback for tabBarLabel (if nested in a TabNavigator) or drawerLabel (if nested in a DrawerNavigator).
headerTitle
String, React Element or React Component used by the header. Defaults to scene title. When a component is used, it receives allowFontScaling, style and children props. The title string is passed in children.
来源:https://stackoverflow.com/questions/52379564/get-string-result-from-function-react-native