react-text-mask与Ant Design Input结合失效问题求助
React-Text-Mask 与 Ant Design Input 掩码失效问题解决方案
在使用 react-text-mask 结合 Ant Design Input 组件实现掩码输入时,掩码功能无法正常生效,推测是 Ref 传递方式错误。尝试了两种 Ref 传递方案均未达到预期效果,现提供正确的实现方式。
初始实现代码
export const MaskedInput = () => ( <TextMask mask={[/\d/, /\d/, /\d/, /\d/, /\d/, /\d/]} render={(textMaskRef, props) => ( <Input {...props} ref={(inputRef) => { inputRef && textMaskRef(inputRef?.input); }} /> )} placeholder="4 numbers" /> );
尝试改进后的 Ref 传递代码
export const MaskedInput = React.memo(React.forwardRef((props, ref) => ( <TextMask mask={[/\d/, /\d/, /\d/, /\d/, /\d/, /\d/]} render={(textMaskRef, props) => ( <Input {...props} ref={(inputRef) => { if (inputRef?.input) { textMaskRef(inputRef?.input); if (ref) { ref.current = inputRef?.input; } } }} /> )} /> )));
正确实现方案
Ant Design 的 Input 组件是原生输入框的封装,其原生 DOM 元素需通过 inputRef 属性获取,而非直接使用 ref(ref 获取的是组件实例而非原生输入元素)。调整 Ref 传递方式如下:
import React from 'react'; import TextMask from 'react-text-mask'; import { Input } from 'antd'; export const MaskedInput = React.forwardRef((props, ref) => ( <TextMask {...props} mask={[/\d/, /\d/, /\d/, /\d/, /\d/, /\d/]} render={(textMaskProps, textMaskRef) => ( <Input {...textMaskProps} inputRef={(nativeInput) => { // 将原生输入框引用传给 react-text-mask textMaskRef(nativeInput); // 向父组件暴露原生输入框引用 if (ref) { ref.current = nativeInput; } }} /> )} /> ));
核心要点:
- 使用 AntD
Input的inputRef属性获取原生输入框 DOM,而非组件实例的ref。 - 在
TextMask的render回调中,确保textMaskRef接收到原生输入框的引用,这样掩码逻辑才能正确绑定。 - 通过
React.forwardRef将原生输入框的 ref 传递给父组件,保证组件的可复用性与外部可访问性。
内容的提问来源于stack exchange,提问作者Lisan Li
相关产品推荐
相关产品推荐

