问题
I wonder there's a way to using headerRight onPress
to doing something like calling Alert
:
I have a function inside MyPet.js
with the code :
_alert=()=>{
alert('saving')
}
and in router.js
I have a list of all screen I've used to navigating with a piece of code like :
export const MyPatientStack = StackNavigator({
MyPatient: {
screen: MyPatient,
navigationOptions: {
tabBarLabel: 'My Patient',
tabBarIcon: ({ tintColor, focused }) => <FontAwesome name="wheelchair" size={25} color={tintColor} />,
headerTitle: 'My Patient',
headerStyle: {
backgroundColor: '#8B0000',
},
headerLeft: <HeaderBackButton tintColor="#FFF" onPress={() => navigation.goBack()} />,
// and here I want to call the function of _alert() from MyPet.js
headerRight: <FontAwesome name='search' size={20} color="#FFF" onPress={_alert()}/>,
headerTintColor: '#fff',
headerTitleStyle: {
fontWeight: 'bold',
textAlign:'center',
flex:1
},
}
}
})
Have tried it and the code doesn't find variable _alert
How can I do that?
any feedback are welcome
回答1:
Since your Navigation component has no reference to what is in your Pet.js
component, you may try the following way
Use navigationOptions
in your Pet.js
component as
// Inside the class
// Since navigationOptions have no access to this parameter of the class, therefore you need to pass them as params
static navigationOptions = ({navigation}) => {
const {params}} = navigation.state;
return {
headerRight: <FontAwesome name='search' size={20} color="#FFF" onPress={() => params.showAlert()}/> />
};
};
componentDidMount() {
this.props.navigation.setParams({
showAlert: this.alertShower
});
}
alertShower = () => Alert.alert('Success', 'Hello')
来源:https://stackoverflow.com/questions/49670528/react-navigation-how-to-calling-function-from-another-file-and-use-it-on-heade