我有一个React Native应用,其中我正在使用React Navigation v3。我想按特定的标签栏创建一个事件。在我的主页标签栏上,我有一个条形码扫描仪。当用户进行扫描时,该应用程序会转到条形码数据将其设置为异步存储的其他选项卡。但是当我尝试再次扫描时,该应用程序将变为空白。
因此,我想创建一个事件,当用户转到“主页”选项卡再次扫描时,可以清除异步存储。如何在首页标签栏上添加该事件?
答案 0 :(得分:1)
尝试以下代码将为您提供帮助,
$B$1
import {NavigationEvents} from "react-navigation";
<NavigationEvents
onWillFocus={payload => console.log('will focus',payload)}
onDidFocus={payload => console.log('did focus',payload)}
onWillBlur={payload => console.log('will blur',payload)}
onDidBlur={payload => console.log('did blur',payload)}
/>
组件可以添加到页面的渲染方法中,您要在其中跟踪用户事件,并像NavigationEvents
这样处理您想要的任何操作。
仅在不需要全部活动时添加一个活动
有关更多详细信息,您可以访问here
谢谢
答案 1 :(得分:0)
您可以监听navigation lifecycle事件。
进行设置非常简单。这是如何在屏幕上进行设置的示例。
import React, {Component} from 'react';
import { View, StyleSheet, Text } from 'react-native';
export default class Screen2 extends React.Component {
// willFocus - the screen will focus
// didFocus - the screen focused (if there was a transition, the transition completed)
// willBlur - the screen will be unfocused
// didBlur - the screen unfocused (if there was a transition, the transition completed)
componentDidMount () {
// add listener
this.willFocusSubscription = this.props.navigation.addListener('willFocus', this.willFocusAction);
this.didFocusSubscription = this.props.navigation.addListener('didFocus', this.didFocusAction);
this.willBlurSubscription = this.props.navigation.addListener('willBlur', this.willBlurAction);
this.didBlurSubscription = this.props.navigation.addListener('didBlur', this.didBlurAction);
}
componentWillUmount () {
// remove listener
this.willFocusSubscription.remove()
this.didFocusSubscription.remove();
this.willBlurSubscription.remove();
this.didBlurSubscription.remove();
}
willBlurAction = () => {
console.log('willBlur Screen', new Date().getTime())
}
didBlurAction = () => {
console.log('didBlur Screen', new Date().getTime());
}
didFocusAction = () => {
console.log('didFocus Screen', new Date().getTime());
}
willFocusAction = () => {
console.log('willFocus Screen', new Date().getTime());
}
render() {
return (
<View style={styles.container}>
<Text>Screen</Text>
</View>
)
}
}
您不需要添加所有侦听器,只需添加所需的侦听器。
您很可能希望在AsyncStorage
事件中从willFocus
清除值。这样,它就可以在屏幕聚焦之前发生。