javascript - 在 React Navigation 中,当每个屏幕获得焦点时,对所有屏幕执行相同的函数
我如何在每个屏幕上使用 React Navigation 执行相同的功能?我正在使用 React Native 和 TypeScript。我有一个包含 home、profile 等的导航。
我有以下函数,我希望在你导航到 profile、home 等时执行它。
const getFunction = (): void => {
console.log("execute function");
};
我尝试了下面的代码,但它不起作用:
useEffect(() => {
const listener = navigation.addListener("focus", (e) => {
getFunction();
});
return () => listener;
}, [navigation]);
我的屏幕概览:
return (
...
<Stack.Screen
name='home'
component={home}
/>
<Stack.Screen
name='profile'
component={profile}
/>
...
)
如果你能帮我,我将非常感激!!:)
答案#1
你可以在导航器上使用 screenListeners 属性。通过这种方式,你可以为所有屏幕的事件指定监听器。示例如下:
<Stack.Navigator
screenListeners={{
focus: (e) => {
// code you wanna execute goes here
console.log("Focus has changed")
},
}}
>
<Stack.Screen name="home" component={home} />
<Stack.Screen name="profile" component={profile} />
</Stack.Navigator>
