我们正在开发 React Native 项目。在那里,我们也在其中显示选项卡栏和侧边栏。 因此,对于该侧栏,我们添加了 react 导航库。但是,在 Android 中,如果用户点击该设备的后退按钮,如果抽屉打开,我们必须将其关闭。
因此,我们在 componentDidMount()
中添加 addListener,并在 componentWillUnmount()
中删除它。
但是,问题是,如果我切换到另一个选项卡并返回到上一个选项卡,并且如果我们点击设备后退按钮,则由于监听器而未调用的后退按钮处理程序将被删除。
一旦我们切换到上一个屏幕,是否有任何替代方法将始终调用该方法。
我们知道,componentDidMount 仅在该屏幕启动时调用一次。
我们知道我们可以调用 render 方法,但是,我们希望通过良好的实践来调用它。
And is there any way to make it global way instead of writing call the classes closing drawer.
代码:
componentDidMount() {
BackHandler.addEventListener('backTapped', this.backButtonTap);
}
componentWillUnmount() {
BackHandler.removeEventListener('backTapped', this.backButtonTap);
}
backButtonTap = () => {
navigation.dispatch(DrawerActions.closeDrawer());
}
有什么建议吗?
最佳答案
我建议使用react-navigation自己的导航生命周期监听器,这样你也可以处理不同页面上不同的后退按钮行为。
componentDidMount() {
this.willFocusListener = navigation.addListener('willFocus', () => {
BackHandler.addEventListener('backTapped', this.backButtonTap);
});
this.willBlurListener = navigation.addListener('willBlur', () => {
BackHandler.removeEventListener('backTapped', this.backButtonTap);
});
}
componentWillUnmount() {
this.willFocusListener.remove();
this.willBlurListener.remove();
}
然后NavigationEvents component也可能有帮助
关于javascript - 在 React Native 中哪里调用 addListener,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55589914/