复制步骤:
预期结果:handleBackButtonClick被调用
实际结果:没有调用handleBackButtonClick
我的代码:
import { BackHandler } from 'react-native';
componentWillMount() {
AppState.addEventListener('change', this.handleAppStateChange);
}
componentWillUnmount() {
AppState.removeEventListener('change', this.handleAppStateChange);
}
handleAppStateChange = (state: AppStateStatus) => {
if (state === 'active') {
console.log('LISTEN');
BackHandler.addEventListener('hardwareBackPress', this.onBackPress);
} else {
console.log('UNLISTEN');
BackHandler.removeEventListener('hardwareBackPress', this.onBackPress);
}
};
handleBackButtonClick = () => {
console.log('press back')
this.props.navigation.goBack(null);
return true;
}
答案 0 :(得分:0)
我有点不确定您要完成什么,但是基于BackHandler上的本机文档,您可能需要将eventListener
放在componentDidMount
上以确保安全。然后,您的处理程序通常会决定如何退回例如
componentDidMount() {
BackHandler.addEventListener('hardwareBackPress', this.handleBackPress);
}
componentWillUnmount() {
BackHandler.removeEventListener('hardwareBackPress', this.handleBackPress);
}
handleBackPress = () => {
this.goBack(); // works best when the goBack is async
return true;
}
此外,除非在您的上下文中另外定义,this.onBackPress
就是undefined
。