我有一个带有堆栈导航器的简单应用程序。导航像
Screen A --> Screen B --> Screen C --> Screen D
我在屏幕B中添加了这样的后处理程序
componentDidMount() {
BackHandler.addEventListener('hardwareBackPress', this.handleBackButtonClick);
}
componentWillUnmount() {
BackHandler.removeEventListener('hardwareBackPress', this.handleBackButtonClick);
}
它在屏幕B上按预期工作。当导航到C或D时,硬件按钮不会分别导致导航回B或C。相反,它似乎触发了屏幕B中的handleBackButtonClick。如何避免这种情况?
React Navigation保持先前的屏幕呈现。因此,您需要确保仅在焦点屏幕中启用后处理程序。
官方文档对此进行了介绍。
对于v4:https://reactnavigation.org/docs/en/custom-android-back-button-handling.html
对于v5:https://reactnavigation.org/docs/en/next/custom-android-back-button-handling.html
我认为在您的情况下,代码可以简化:
handleBackButtonClick = () => {
// If this screen is not focused, don't do anything
if (!this.props.navigation.isFocused()) {
return false;
}
// Do what you're doing
}
``
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句