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