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

React Native函数组件中TextInput输入后自动聚焦下一个输入框的实现方法

问题根因

你当前遇到的核心问题是自定义函数组件的ref没有正确透传到内部的原生TextInput,导致你拿到的inputRef.current不是原生输入框实例,调用focus()方法无效,同时自定义组件没有透传你传入的keyboard、max等配置属性。

解决步骤

步骤1:修改自定义Input组件,用forwardRef透传ref和属性

使用React.forwardRef包裹你的自定义Input组件,接收外部传入的ref并绑定到内部的TextInput上,同时补全需要透传的属性:

import React from 'react';
import { TextInput } from 'react-native';

// 用forwardRef包裹组件,第二个参数为外部传入的ref
const Input = React.forwardRef((props, ref) => {
  // 保留你原有颜色控制逻辑
  const [color, setColor] = React.useState(Colors.gry);

  return (
    <TextInput
      onChangeText={(text) => props.onChange(text)}
      value={props.value}
      placeholder={props.placeholder}
      placeholderTextColor={color}
      autoFocus={!!props.focus}
      onFocus={() => setColor(Colors.org)}
      onBlur={() => setColor(Colors.gry)}
      ref={ref} // 绑定外部传入的ref,不要使用props.ref
      returnKeyType='next'
      // 透传外部传入的配置属性
      keyboardType={props.keyboard}
      maxLength={props.max}
    />
  )
})

export default Input;

步骤2:优化业务代码的聚焦逻辑

在第一个输入框的输入回调里增加长度判断,输入满1位(即你设置的max长度)时再触发下一个输入框的聚焦,可选链操作符?.可以避免ref未绑定完成时报错:

import React, { useRef, useState } from 'react';
import { View } from 'react-native';

const 你的业务组件 = () => {
  const inputRef = useRef(null);
  const [otp, setOtp] = useState({ o1: '', o2: '' });

  return (
    <View>
      <View style={styles.input}>
        <Input
          keyboard={'numeric'}
          onChange={(text) => {
            setOtp({ ...otp, o1: text })
            // 输入满1位自动跳转下一个输入框
            if (text.length === 1) {
              inputRef.current?.focus()
            }
          }}
          value={otp.o1}
          max={1}
        />
      </View>
      <View style={styles.input}>
        <Input
          keyboard={'numeric'}
          onChange={(text) => setOtp({ ...otp, o2: text })}
          value={otp.o2}
          ref={inputRef}
          max={1}
        />
      </View>
    </View>
  )
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 11:15:03