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

React Native调用用户闲置检测自定义组件报错如何解决?

问题排查与修复方案

1. 导航代码语法错误

你给出的MainNavigator函数中缺失<Stack.Navigator>开启标签,属于JSX语法错误,是最直接的报错原因:

/** Main route 修正前代码 */
const MainNavigator = () => {
  return (
      // 此处缺失<Stack.Navigator>开启标签
      <Stack.Screen
        name="Schedule"
        component={ScheduleScreen}
        options={{
          header: () => null,
        }}
      />
    </Stack.Navigator>
  );
};

修复后代码:

const MainNavigator = () => {
  return (
    <Stack.Navigator> // 补全开启标签
      <Stack.Screen
        name="Schedule"
        component={ScheduleScreen}
        options={{
          header: () => null,
        }}
      />
    </Stack.Navigator>
  );
};

2. PanResponder回调未返回布尔值

React Native的onStartShouldSetPanResponderCapture回调要求必须返回布尔值,用于声明是否要抢占触摸事件响应权,你当前的代码没有返回值,会导致触摸事件逻辑异常:

// 修正前
onStartShouldSetPanResponderCapture: () => {
  console.tron.log('user starts touch');
  resetInactivityTimeout();
},

修复后代码:

onStartShouldSetPanResponderCapture: () => {
  console.tron.log('user starts touch');
  resetInactivityTimeout();
  // 不需要拦截事件传递给子组件就返回false,需要全局拦截触摸就返回true
  return false;
},

3. 潜在的未定义报错风险

console.tron是Reactotron调试工具注入的属性,如果你没有在项目中正确配置Reactotron,调用console.tron.log会直接抛出未定义错误,建议替换为原生console.log或者确认Reactotron已完成初始化配置。

4. 可选优化点

  • 组件名拼写修正:ScreenConponent拼写有误,正确应为ScreenComponent,避免后续导入时出现路径匹配错误
  • 定时器ref初始化优化:将const timerId = useRef(false)改为const timerId = useRef(null),和定时器API的默认返回值类型匹配,避免clearTimeout传入非合法参数的潜在警告
  • 组件逻辑解耦:把超时后的闲置处理逻辑通过props暴露给调用方,不用写死在组件内,提升组件复用性

内容的提问来源于stack exchange,提问作者Rachman Pratama

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 00:48:03