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

React-Text-Mask集成Material UI TextField报错求助

React-Text-Mask 结合 Material UI TextField 的 Ref 问题解决方案

你遇到的警告是因为 Material UI 的 InputBase 要求 inputComponent 必须是一个能接收 ref 的组件,而你定义的 PhoneInput 是普通函数组件,默认不支持 ref 传递。

修改后的代码

将 PhoneInput 用 React.forwardRef 包裹,就能正确传递 ref 给内部的 MaskedInput:

import React, { forwardRef } from 'react';
import { TextField } from "@mui/material";
import { MaskedInput } from "react-text-mask";

// 使用 forwardRef 包装组件,接收 ref 作为第二个参数
const PhoneInput = forwardRef((props, ref) => (
    <MaskedInput
        {...props}
        ref={innerRef => {
            // 将内部输入框的 ref 传递给外部的 ref
            if (ref) {
                ref(innerRef ? innerRef.inputElement : null);
            }
        }}
        mask={['(', /[1-9]/, /\d/, /\d/, ')', ' ', /\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/]}
        placeholderChar={'\\u2000'}
    />
));

export const FormTelephone = (props) => {
    return (
        <TextField label="Telephone" InputProps={{ inputComponent: PhoneInput }} />
    );
};

关键修改说明

  • 导入 React.forwardRef,用它包裹 PhoneInput 组件,组件参数变为 (props, ref)
  • 替换原来的 inputRef 为 forwardRef 提供的 ref 参数,确保 ref 能正确传递到 MaskedInput 对应的真实 DOM 输入元素上

网上示例能正常运行,大概率是因为示例中已经使用了 forwardRef 处理 ref 传递,只是你没注意到这个细节。当前版本的 MUI 对 inputComponent 的 ref 支持有严格要求,普通函数组件无法满足需求,必须通过 forwardRef 包装让组件具备接收 ref 的能力。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 08:28:15