问题
//TermsPage.tsx
const resetAction = StackActions.reset({
index: 0,
actions: [NavigationActions.navigate({
routeName: 'BottomTabNav',
params:{showTerms:false}
}),
],
});
componentWillUnmount() {
BackHandler.addEventListener('hardwareBackPress',()=>{
this.props.navigation.dispatch(resetAction)
return true
})
}
How to set 'hardwareBackPress' eventListenner to navigate to another StackNavigator. If I set like above. This backpress work in all Pages. I want to set this listener only for TermsPage. And set this listener to navigate to another StackNavigator
回答1:
I solve this problem with function pop()
.
In the page, where I want to go another stack I added
const resetAction = StackActions.reset({
index: 0,
actions: [NavigationActions.navigate({
routeName: 'BottomTabNav',
params:{showTerms:false}
}),
],
});
handleBackButtonClick() {
this.props.navigation.dispatch(resetAction);
return true;
}
And in another pages
handleBackButtonClick() {
// @ts-ignore
this.props.navigation.pop();
return true;
}
``` And voila
回答2:
you can use this example, here we bind this method in Constructer and also call this function whenever the screen is rendering back
constructor(props) {
super(props);
this.handleBackButtonClick = this.handleBackButtonClick.bind(this);
this.state = {
};
}
componentWillMount() {
BackHandler.addEventListener(
'hardwareBackPress',
this.handleBackButtonClick,
);
}
componentWillUnmount() {
BackHandler.removeEventListener(
'hardwareBackPress',
this.handleBackButtonClick,
);
}
handleBackButtonClick() {
this.props.navigation.navigate('name of page where you want to nav');
return true;
}
From where you don't want to go back use this..
componentWillUnmount() {
BackHandler.removeEventListener('hardwareBackPress', this.handleBackButton);
}
componentDidMount() {
BackHandler.addEventListener('hardwareBackPress', this.handleBackButton);
}
handleBackButton() {
return true;
}
It will not let you go back from the page where you are, please import BackHandler from react-native. hope it helps, feel free for Doubts.
来源:https://stackoverflow.com/questions/60202096/how-to-set-hardwarebackpress-to-another-stack