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

React Native Android中TextInput唤起键盘后立即收起问题求助

Android端React Native TextInput点击后键盘弹出随即收起(与@react-navigation相关)

问题描述

React Native应用中的多个TextInput组件在iOS上运行正常,但在Android端点击输入框后,键盘弹出随即收起,无法输入。经调试定位到问题由@react-navigation库导致——将TextInput放在NavigationContainer外可正常运行。

复现代码

  • 测试页面组件
const TestScreen = () => {
  return (
    <TextInput
      label="Phone number"
      mode="outlined"
      theme={{colors: {primary: COLORS.primary}}}
      keyboardType="number-pad"
      left={<TextInput.Icon name="phone" />}
    />
  );
};
  • 底部标签导航器
const Tabs = () => {
  return (
      <Tab.Navigator
          initialRouteName="Home"
         tabBarOptions={{
            activeTintColor: COLORS.primary,
           inactiveTintColor: COLORS.darkgray,
            showLabel: false,
          }}>
          <Tab.Screen name="Home" component={Home} />
          <Tab.Screen name="Test" component={TestScreen} />
          <Tab.Screen name="User" component={Profile} />
        </Tab.Navigator>
  );
};
  • 导航容器配置
<NavigationContainer theme={theme} onReady={() => RNBootSplash.hide()}>
  <Stack.Navigator
    screenOptions={{   
      headerShown: false,
    }}
    initialRouteName={'Home'}>
    <Stack.Screen name="Home" component={Tabs} />
  </Stack.Navigator>
</NavigationContainer>

当前依赖版本

"@react-navigation/bottom-tabs": "^5.11.2",
"@react-navigation/native": "^5.8.10",
"@react-navigation/stack": "^5.12.8",
"react-native-screens": "^3.15.0",

解决方案

1. 禁用react-native-screens的Android特定优化

react-native-screens在Android上的部分特性可能与TextInput焦点逻辑冲突,可在项目入口文件(如App.js)顶部添加代码禁用该优化:

import { enableScreens } from 'react-native-screens';
enableScreens(false);

2. 调整依赖版本匹配度

导航库与react-native-screens版本不兼容是常见诱因,可尝试两种调整方式:

  • 降级react-native-screens到与导航v5兼容的稳定版本:
npm install react-native-screens@2.15.0
# 或使用yarn:yarn add react-native-screens@2.15.0
  • 升级@react-navigation相关包到v5分支的最新版本:
npm update @react-navigation/native @react-navigation/bottom-tabs @react-navigation/stack

3. 优化导航容器的onReady回调

onReady中的启动页隐藏逻辑可能干扰焦点获取,可尝试延迟执行或临时移除测试:

onReady={() => setTimeout(() => RNBootSplash.hide(), 200)}

4. 手动控制TextInput焦点状态

通过状态管理强制保持TextInput的焦点,避免导航触发的焦点丢失:

import { useState } from 'react';
import { TextInput } from 'react-native-paper';

const TestScreen = () => {
  const [isFocused, setIsFocused] = useState(false);

  return (
    <TextInput
      label="Phone number"
      mode="outlined"
      theme={{colors: {primary: COLORS.primary}}}
      keyboardType="number-pad"
      left={<TextInput.Icon name="phone" />}
      onFocus={() => setIsFocused(true)}
      onBlur={() => setIsFocused(false)}
      autoFocus={isFocused}
    />
  );
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 23:54:04