react-native - 每次组件成为 react-native 中的事件选项卡时调用函数

标签 react-native navigation

我想触发一个功能,每次组件在底部导航 react-native 中变为 事件选项卡。有人可以给我一个解决方案吗?

最佳答案

Navigation events 中使用 focus如下

componentDidMount() {
    this.focusListener = this.props.navigation.addListener('focus',
        () => alert('Screen focused'))
}

确保移除监听器

componentWillUnmount() {
    this.focusListener.remove();
}

有关更多信息,请查看下面的示例

import React, { Component } from "react";
import { Text, View } from "react-native";
import { NavigationContainer } from "@react-navigation/native";
import { createBottomTabNavigator } from "@react-navigation/bottom-tabs";

class HomeScreen extends Component {
  componentDidMount() {
    this.focusListener = this.props.navigation.addListener("focus", () =>
      alert("Screen home")
    );
  }

  componentWillUnmount() {
    this.focusListener.remove();
  }

  render() {
    return (
      <View style={{ flex: 1, justifyContent: "center", alignItems: "center" }}>
        <Text>Home</Text>
      </View>
    );
  }
}

class SettingsScreen extends Component {
  render() {
    return (
      <View style={{ flex: 1, justifyContent: "center", alignItems: "center" }}>
        <Text>Settings</Text>
      </View>
    );
  }
}

const Tab = createBottomTabNavigator();

export default function App() {
  return (
    <NavigationContainer>
      <Tab.Navigator>
        <Tab.Screen name="Home" component={HomeScreen} />
        <Tab.Screen name="Settings" component={SettingsScreen} />
      </Tab.Navigator>
    </NavigationContainer>
  );
}

希望对您有所帮助。如有疑问,请随意。

关于react-native - 每次组件成为 react-native 中的事件选项卡时调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60128851/

相关文章:

ios - SWRevealViewController 不切换

java - 如何从 Package Explorer 关闭 Eclipse 自动扩展 JRE 类?

ios - 模块 AppRegistry 不是注册的可调用模块

android - react-native 上的 Realm : can't get results when not debugging

webview - 如何在 React Native 的 WebView 中使用源而不是 html

javascript - 如何使用flexbox和React-Native让裁剪后的图像填充所有View?

reactjs - 如何获取react-native中的DataSource长度?

ios - Web 查看后退按钮历史记录

react-native - 如何在 native react 中将状态传递给静态导航?

jsf primefaces 进度条更新值,而 Action 方法正在运行