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

React Native验证码输入组件首次渲染自动唤起键盘方案咨询

实现react-native-confirmation-code-field渲染后自动唤起键盘并聚焦第一个单元格

我正在使用react-native-confirmation-code-field包,希望在屏幕渲染完成后立即唤起键盘,且让第一个输入单元格获得焦点。以下是我的代码:

export default function ConfirmationCode({ route, navigation }) {

  const [value, setValue] = useState("")
  const ref = useBlurOnFulfill({ value, cellCount: CELL_COUNT })
  const [props, getCellOnLayoutHandler] = useClearByFocusCell({value, setValue})

  return (
        <CodeField
          ref={ref}
          {...props}
          value={value}
          onChangeText={setValue}
          cellCount={CELL_COUNT}
          rootStyle={styles.codeFieldRoot}
          keyboardType="number-pad"
          textContentType="oneTimeCode"
          renderCell={({ index, symbol, isFocused }) => (
            <Text
              key={index}
              style={[styles.cell, isFocused && styles.focusCell]}>
              {symbol || (isFocused ? <Cursor /> : null)}
            </Text>
          )
          }
        />
    )
}

实现方案

  • 借助useEffect和组件ref主动触发聚焦
    组件挂载完成后,通过useEffect钩子调用CodeField实例的focus方法,直接让第一个输入单元格获得焦点,同时唤起键盘。react-native-confirmation-code-field的CodeField组件原生支持focus方法,可直接调用。

  • 修改后的完整代码
    在原代码中添加useEffect逻辑:

import { useEffect, useState } from 'react';
// 保持其他导入不变

export default function ConfirmationCode({ route, navigation }) {
  const [value, setValue] = useState("")
  const ref = useBlurOnFulfill({ value, cellCount: CELL_COUNT })
  const [props, getCellOnLayoutHandler] = useClearByFocusCell({value, setValue})

  useEffect(() => {
    // 组件挂载后立即聚焦第一个单元格
    ref.current?.focus();
  }, []);

  return (
        <CodeField
          ref={ref}
          {...props}
          value={value}
          onChangeText={setValue}
          cellCount={CELL_COUNT}
          rootStyle={styles.codeFieldRoot}
          keyboardType="number-pad"
          textContentType="oneTimeCode"
          renderCell={({ index, symbol, isFocused }) => (
            <Text
              key={index}
              style={[styles.cell, isFocused && styles.focusCell]}>
              {symbol || (isFocused ? <Cursor /> : null)}
            </Text>
          )
          }
        />
    )
}
  • 注意事项
    • 使用可选链操作符?.是为了避免组件未完全挂载时调用focus方法导致报错。
    • 如果CELL_COUNT是动态变化的值,需要将其添加到useEffect的依赖数组中,确保数值变更时能重新触发聚焦逻辑。
    • 部分iOS/Android系统可能限制应用自动唤起键盘,这种情况下该逻辑可能失效,需要用户手动点击输入框,但大部分常规场景下上述代码可以正常工作。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 18:05:26