在 React 导航 v6 中,您需要做的就是
import { useIsFocused } from '@react-navigation/native';
function Profile() {
const isFocused = useIsFocused();
return <Text>{isFocused ? 'focused' : 'unfocused'}</Text>;
}
参考 v6.x:https://reactnavigation.org/docs/use-is-focused
老年人:
使用react-navigation,您可以分两步完成:
-
在componentDidMount或componentWillMount中添加监听器,以钩住事件
-
移除componentWillUnmount 中的监听器,避免意外调用
API 参考文档 v3.x、v4.x、v5.x:
React-navigation v3.x、v4.x:
addListener - 订阅导航生命周期的更新
React Navigation 向订阅的屏幕组件发出事件
他们:
-
willFocus - 屏幕将聚焦
-
didFocus - 屏幕聚焦(如果有过渡,则过渡完成)
-
willBlur - 屏幕将失焦
-
didBlur - 屏幕失焦(如果有过渡,则过渡完成)
React-navigation 3.x、4.x示例:
const didBlurSubscription = this.props.navigation.addListener(
'didBlur',
payload => {
console.debug('didBlur', payload);
}
);
// Remove the listener when you are done
didBlurSubscription.remove();
参考 v4.x https://reactnavigation.org/docs/4.x/navigation-prop/#addlistener---subscribe-to-updates-to-navigation-lifecycle
更新的 v5.x
事件已在 v5.x 中更改
屏幕可以在
类似于 React Navigation 中的导航道具。默认有2个
可用事件:
- focus - 当屏幕聚焦时触发此事件
- blur - 当屏幕失焦时触发此事件
- state (advanced) - 当导航器的状态改变时触发此事件
来自 reactnavigation.org 的示例代码
class Profile extends React.Component {
componentDidMount() {
this._unsubscribe = navigation.addListener('focus', () => {
// do something
});
}
componentWillUnmount() {
this._unsubscribe();
}
render() {
// Content of the component
}
}
与钩子一起使用
function Profile({ navigation }) {
React.useEffect(() => {
const unsubscribe = navigation.addListener('focus', () => {
// do something
});
return unsubscribe;
}, [navigation]);
return <ProfileContent />;
}
屏幕上的侦听器道具
<Tab.Screen
name="Chat"
component={Chat}
listeners={({ navigation, route }) => ({
tabPress: e => {
// Prevent default action
e.preventDefault();
// Do something with the `navigation` object
navigation.navigate('AnotherPlace');
},
})}
/>
参考 v5.x:https://reactnavigation.org/docs/navigation-events