如何在点击提交按钮后清空react-pin-input的输入值?
解决react-pin-input提交后清空输入值的问题
方法一:调用组件内置的reset方法
react-pin-input组件内部维护自身状态,直接修改ref.current.value无效,你可以通过ref调用组件提供的reset方法来清空输入:
- 确保ref初始化正确:
import { useRef } from 'react'; import PinInput from 'react-pin-input'; // 初始化ref const pintInputRef = useRef(null);
- 在提交方法中调用reset:
const handleSubmit = () => { // 调用reset清空输入框 pintInputRef.current?.reset(); };
方法二:改为受控组件,通过状态控制
如果组件支持受控模式,可通过状态绑定输入值,提交后重置状态实现清空:
- 初始化状态:
import { useState } from 'react'; const [otpValue, setOtpValue] = useState('');
- 修改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_@./#&+-]*$/} />
- 提交时重置状态:
const handleSubmit = () => { // 重置状态清空输入 setOtpValue(''); };
注意:使用受控模式前,请确认你使用的react-pin-input版本支持
value和onChange属性。
内容的提问来源于stack exchange,提问作者bbt-lover
相关产品推荐
相关产品推荐

