FLa*_*ash 2 react-native react-navigation
我有一个带有堆栈导航器的简单应用程序。其导航方式如下
Screen A --> Screen B --> Screen C --> Screen D
我在屏幕 B 中添加了一个后台处理程序,如下所示
componentDidMount() {
BackHandler.addEventListener('hardwareBackPress', this.handleBackButtonClick);
}
componentWillUnmount() {
BackHandler.removeEventListener('hardwareBackPress', this.handleBackButtonClick);
}
Run Code Online (Sandbox Code Playgroud)
它在屏幕 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
}
``
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2000 次 |
| 最近记录: |