带有 Material UI 的 React-Text-Mask 不起作用

问题描述 投票:0回答:1

我们已经看过一百万种不同的方法,但无法让它以任何一种方式工作。我想将react-text-mask与material UI一起使用,但我得到的只是错误和挫败感,所以这是我最新的尝试:

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

const PhoneInput = ({ inputRef, ...props }) => (
    <MaskedInput
        {...props}
        ref={ref => { inputRef(ref ? ref.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}} />
    </>)
}

应用程序出现错误:

Warning: Failed prop type: Invalid prop `inputComponent` supplied to `ForwardRef(InputBase)`. Expected an element type that can hold a ref. Did you accidentally provide a plain function component instead? For more information see https://mui.com/r/caveat-with-refs-guide

我不明白所有这些是如何在线工作的,但我被困住了。有什么建议吗?

reactjs material-ui
1个回答
0
投票

从 Material UI v4 升级到 v5 后,我遇到了同样的问题。问题的出现是因为 v5 中不再定义

inputRef
属性。相反,他们转发一个函数来设置参考。

旧版本(@material-ui v4)

import React from 'react';
import MaskedInput from 'react-text-mask';

const PhoneInput = ({inputRef, ...props}) => {
  return (
    <MaskedInput
      mask={['(', /[1-9]/, /\d/, /\d/, ')', ' ', /\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/]}
      placeholderChar={'\u2000'}
      ref={ref => {
        inputRef(ref ? ref.inputElement : null);
      }}
      {...props}
    />
  );
};

export default PhoneInput;

新版本(@mui v5)

import React, {forwardRef} from 'react';
import MaskedInput from 'react-text-mask';

const PhoneInput = forwardRef((props, ref) => {
  return (
    <MaskedInput
      mask={['(', /[1-9]/, /\d/, /\d/, ')', ' ', /\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/]}
      placeholderChar={'\u2000'}
      ref={innerRef => {
        if (innerRef) {
          setRef(innerRef.inputElement);
        }
      }}
      {...props}
    />
  );
});

export default PhoneInput;
© www.soinside.com 2019 - 2024. All rights reserved.