React Hook Form结合MUI TextField使用InputMask的Ref警告问题
问题描述
将MUI的TextField组件与react-input-mask的MaskInput组件及React Hook Form结合使用时,功能正常但控制台弹出StrictMode下的Ref相关警告,尝试过useRef钩子、直接选择输入框、useEffect注册输入框等方法,警告仍未消除。
控制台错误信息
react-dom.development.js:86 Warning: findDOMNode is deprecated in StrictMode. findDOMNode was passed an instance of InputElement2 which is inside StrictMode. Instead, add a ref directly to the element you want to reference.
相关代码
import { useFormContext, Controller } from "react-hook-form"; import { Grid, TextField } from "@mui/material"; import InputMask from "react-input-mask"; const FormInputMask = ({ name, label }) => { const { control } = useFormContext(); return ( <Grid item xs={12}> <Controller control={control} name={name} defaultValue="" render={({ field }) => ( <InputMask {...field} maskChar="" mask="999 999" label={label} variant="outlined" fullWidth={true} > {(inputProps) => ( <TextField {...inputProps} /> )} </InputMask> )} /> </Grid> ); }; export default FormInputMask;
解决方案
这个警告是因为react-input-mask在StrictMode下内部使用了已被废弃的findDOMNode方法获取DOM元素,核心解决思路是手动将ref正确传递到底层原生input元素,同时调整属性传递逻辑:
- 用
forwardRef包装MUI TextField,确保ref能绑定到原生input节点(MUI TextField的ref指向外层组件容器,需用inputRef绑定原生input) - 从React Hook Form的
field中解构出ref,手动传递给InputMask和内层TextField - 将原本传给InputMask的MUI专属属性(如
label、variant)移到TextField上,避免属性传递混乱
修改后的代码如下:
import { useFormContext, Controller } from "react-hook-form"; import { Grid, TextField } from "@mui/material"; import InputMask from "react-input-mask"; import { forwardRef } from "react"; // 包装TextField,确保ref能传递到原生input const MaskedTextField = forwardRef((props, ref) => ( <TextField {...props} inputRef={ref} /> )); const FormInputMask = ({ name, label }) => { const { control } = useFormContext(); return ( <Grid item xs={12}> <Controller control={control} name={name} defaultValue="" render={({ field: { ref, ...fieldProps } }) => ( <InputMask {...fieldProps} maskChar="" mask="999 999" ref={ref} > {(inputProps) => ( <MaskedTextField {...inputProps} label={label} variant="outlined" fullWidth /> )} </InputMask> )} /> </Grid> ); }; export default FormInputMask;
另外,也可以尝试升级react-input-mask到最新版本,部分新版本已针对StrictMode修复了findDOMNode的使用问题,若升级后问题解决,可不用手动处理ref传递。
内容的提问来源于stack exchange,提问作者Stairss
相关产品推荐
相关产品推荐

