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

如何在点击提交按钮后清空react-pin-input的输入值?

解决react-pin-input提交后清空输入值的问题

方法一:调用组件内置的reset方法

react-pin-input组件内部维护自身状态,直接修改ref.current.value无效,你可以通过ref调用组件提供的reset方法来清空输入:

  1. 确保ref初始化正确:
import { useRef } from 'react';
import PinInput from 'react-pin-input';

// 初始化ref
const pintInputRef = useRef(null);
  1. 在提交方法中调用reset:
const handleSubmit = () => {
  // 调用reset清空输入框
  pintInputRef.current?.reset();
};

方法二:改为受控组件,通过状态控制

如果组件支持受控模式,可通过状态绑定输入值,提交后重置状态实现清空:

  1. 初始化状态:
import { useState } from 'react';

const [otpValue, setOtpValue] = useState('');
  1. 修改PinInput为受控模式:
<PinInput
  ref={pintInputRef}
  length={6}
  secret
  type="numeric"
  inputMode="numeric"
  value={otpValue} // 绑定状态值
  onChange={(value) => setOtpValue(value)} // 实时更新状态
  onComplete={(value) => {
    handleOnCompleteInput(value);
  }}
  autoSelect={true}
  regexCriteria={/^[ A-Za-z0-9_@./#&+-]*$/}
/>
  1. 提交时重置状态:
const handleSubmit = () => {
  // 重置状态清空输入
  setOtpValue('');
};

注意:使用受控模式前,请确认你使用的react-pin-input版本支持value和onChange属性。

内容的提问来源于stack exchange,提问作者bbt-lover

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 00:55:20