如何在反应原生的按Tab键上添加事件?

问题描述 投票:1回答:2

我有一个反应原生应用程序,我正在使用反应导航v3。我想在按下特定标签栏时创建一个事件。在我的主页标签栏上,我有条形码扫描仪。当用户扫描时,应用程序将指向不同的选项卡,条形码数据将数据设置为异步存储。但是当我再次尝试扫描时,它变为空白。

因此,我想创建一个事件,当用户转到主页选项卡再次扫描时,我可以清除异步存储。如何在主页标签栏上添加该事件?

react-native react-navigation
2个回答
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组件,您可以在其中跟踪用户的事件,并像AsyncStorage一样处理您想要的任何操作。

如果您不需要全部,只添加一个事件

有关更多详细信息,请访问here

谢谢


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中清除你的价值。这样它就会在屏幕聚焦之前发生。

© www.soinside.com 2019 - 2024. All rights reserved.