You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React-Native类组件结合react-navigation 6.x监听页面聚焦(生命周期失效)

React Navigation 6.x 类组件焦点监听方案

在React Navigation 6.x中,类组件无法直接使用useIsFocused这类Hook,但可以通过以下两种方式实现焦点监听,满足每次组件获得焦点时执行指定函数的需求:

方法一:直接利用navigation prop添加监听

如果你的类组件已经通过路由配置获得了navigation prop,可以直接在生命周期中添加焦点事件监听:

import React, { Component } from 'react';
import { View, Text } from 'react-native';

class TargetComponent extends Component {
  componentDidMount() {
    // 订阅focus事件,保存返回的取消函数
    this.focusSubscription = this.props.navigation.addListener('focus', () => {
      // 组件获得焦点时执行的逻辑
      this.onComponentFocus();
    });
  }

  componentWillUnmount() {
    // 取消订阅,避免内存泄漏
    this.focusSubscription();
  }

  onComponentFocus = () => {
    console.log('组件已获得焦点');
    // 这里编写你的业务处理代码
  };

  render() {
    return (
      <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
        <Text>类组件焦点监听示例</Text>
      </View>
    );
  }
}

export default TargetComponent;

方法二:通过withNavigation注入navigation prop

如果组件没有直接拿到navigation prop,可以使用withNavigation高阶组件将其注入:

import React, { Component } from 'react';
import { View, Text } from 'react-native';
import { withNavigation } from '@react-navigation/native';

class TargetComponent extends Component {
  componentDidMount() {
    this.focusSubscription = this.props.navigation.addListener('focus', () => {
      this.onComponentFocus();
    });
  }

  componentWillUnmount() {
    this.focusSubscription();
  }

  onComponentFocus = () => {
    console.log('组件已获得焦点');
    // 业务逻辑代码
  };

  render() {
    return (
      <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
        <Text>通过withNavigation注入navigation</Text>
      </View>
    );
  }
}

// 用withNavigation包裹组件,注入navigation prop
export default withNavigation(TargetComponent);

关键注意事项

  • 必须在componentWillUnmount中调用订阅返回的取消函数,防止内存泄漏
  • focus事件会在组件每次进入可视区域时触发(包括从后台返回、从其他页面跳转回来),完全覆盖"每次获得焦点"的需求
  • 如果需要监听组件失去焦点,可以替换为blur事件,用法与focus一致

内容的提问来源于stack exchange,提问作者four-eyes

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 05:01:47