You need to enable JavaScript to run this app. React Native 如何为同一全局自定义组件创建多个Ref实现内部TextInput聚焦
优惠活动
大模型
产品
解决方案
定价
更多

React Native 如何为同一全局自定义组件创建多个Ref实现内部TextInput聚焦

自定义函数组件的多Ref绑定实现方案

问题根因

你之前直接在OTPInput上传ref不生效,是因为普通函数式组件默认不会接收外部传入的ref参数——ref不属于常规props的范畴,React不会自动把外部传入的ref和组件内部的DOM/原生组件做绑定,必须手动做透传处理。

第一步:改造封装的OTPInput组件

用React提供的forwardRefAPI把外部传入的ref透传到内部的原生TextInput上,改造后的组件代码:

import { forwardRef } from 'react';

export const OTPInput = forwardRef((props, ref) => {
  return (
    <TextInput
      ref={ref} // 直接将外部传入的ref绑定到原生TextInput实例上
      placeholder={props.title}
      onChangeText={props.onTextEnter}
      value={props.value}
    />
  );
});

第二步:类组件中给多个OTPInput绑定独立Ref

多个OTPInput实例需要对应多个独立的ref对象,避免ref被互相覆盖:

  • 在类组件的构造函数中初始化每个实例对应的ref
  • 给每个OTPInput传入对应的ref
  • 按钮点击逻辑中通过ref拿到内部TextInput实例,直接调用原生的focus方法即可

完整类组件示例代码:

class ABC extends Component {
  constructor(props) {
    super(props);
    // 为两个OTPInput分别创建独立的ref
    this.firstOTPRef = React.createRef();
    this.secondOTPRef = React.createRef();
  }

  // 按钮触发焦点控制示例
  jumpToSecondInput = () => {
    // ref的current属性就是绑定的原生TextInput实例,可选链避免未挂载时报错
    this.secondOTPRef.current?.focus();
  }

  render() {
    return (
      <>
        <OTPInput
          ref={this.firstOTPRef}
          title="first otp"
        />
        <OTPInput
          ref={this.secondOTPRef}
          title="another otp"
        />
        <TouchableOpacity onPress={this.jumpToSecondInput}>
          聚焦第二个OTP输入框
        </TouchableOpacity>
      </>
    );
  }
}

低版本React兼容写法

如果项目中React版本低于16.3,不支持forwardRef,可以把ref作为普通自定义props(比如命名为inputRef)传递,在组件内部绑定到TextInput上,效果完全一致:

// OTPInput低版本写法
export const OTPInput = props => {
  return (
    <TextInput
      ref={props.inputRef}
      placeholder={props.title}
      onChangeText={props.onTextEnter}
      value={props.value}
    />
  );
};

// 类组件中使用时传自定义props即可
<OTPInput
  inputRef={this.firstOTPRef}
  title="first otp"
/>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.23 16:15:07