在本机中调用 addListener 的位置
Where to call addListener in react native
我们正在研究 React Native 项目。在那里,我们在其中显示了标签栏,也显示了侧边栏。
因此,对于那个侧边栏,我们添加了 react-navigation 库。但是,在 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 自己的 Navigation Lifecycle 监听器,这样你也可以在不同的页面上处理不同的后退按钮行为。
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 也有帮助
我们正在研究 React Native 项目。在那里,我们在其中显示了标签栏,也显示了侧边栏。 因此,对于那个侧边栏,我们添加了 react-navigation 库。但是,在 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 自己的 Navigation Lifecycle 监听器,这样你也可以在不同的页面上处理不同的后退按钮行为。
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 也有帮助