如何使用 React Navigation 5 复制 onDidBlur 或 onWillBlur? [英] How to replicate onDidBlur or onWillBlur with React Navigation 5?
问题描述
正如他们在文档中指出的,他们已经摆脱了 4 个导航事件侦听器,而是决定使用 生命周期事件.
As they point out in the docs, they've gotten rid of the 4 navigation event listeners and instead decided to use Lifecycle events.
但是我在使用 React Navigation 5 时遇到的问题是 blur
事件无法按照我的需要工作!之前,我可以添加一个 onWillBlur
侦听器,并在用户暂时离开(而不是关闭)应用程序时执行一些操作(例如关闭套接字连接,然后在用户重新进入应用程序时重新打开它).
But the problem I'm running into with React Navigation 5 is that the blur
event doesn't work as I need it to! Before, I could add an onWillBlur
listener, and do stuff when the user temporarily leaves (not closes) the app (such as close a socket connection, and then reopen it when the user reenters the app).
如何为这样的用例复制 onWillBlur
或 onDidBlur
事件?用户点击按钮后进入屏幕 B 后,我不需要知道屏幕 A 是否模糊.
How can I replicate the onWillBlur
or onDidBlur
events for such a use case? I don't need to know if Screen A is blurred after the user is taken to Screen B after clicking a button.
推荐答案
您可以使用钩子 useFocusEffect.
You can use the hook useFocusEffect.
添加了来自 React Navigation 的示例.
Added example from React Navigation.
import { useFocusEffect } from '@react-navigation/native';
function Profile() {
useFocusEffect(
React.useCallback(() => {
// Do something when the screen is focused, onFocus
return () => {
// Do something when the screen is unfocused, onBlur
// Useful for cleanup functions
};
}, [])
);
return <ProfileContent />;
}
编辑 2:
我没有在主页按钮上测试它,但我发现一个帖子也有帮助
I didn't test it on home button but I found a post that helps with that too
希望这次你对我的回答感到满意.
I hope this time you are pleased with my answer.
这里有一个工作示例:
import React from 'react'
import { Text, AppState } from 'react-native'
const MyComponent = () => {
const [appState, setAppState] = React.useState(AppState.currentState)
React.useEffect(() => {
AppState.addEventListener('change', handleChanges)
setAppState(AppState.currentState)
return AppState.removeEventListener('change')
},[])
const handleChanges = (nextAppState) => {
if (appState.match(/inactive|background/) && nextAppState === 'active') {
console.log('App has come to the foreground!');
} else {
console.log('App has gone to the background!');
// start your background task here
}
setAppState(nextAppState)
}
return <Text>{appState}</Text>
}
这篇关于如何使用 React Navigation 5 复制 onDidBlur 或 onWillBlur?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!