gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 01:13:36 24 4
gpt4 key购买 nike

我想触发一个功能,每次组件在底部导航 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com