【问题标题】:MaskedInput text is not correctly displayed when it received through the props通过 props 接收到 MaskedInput 文本时无法正确显示
【发布时间】:2021-08-14 17:41:06
【问题描述】:

我有一个 Material UI OutlinedInput 在其上使用 MaskedInputfrom react-text-mask,当我最初将文本放入其中并且元素未聚焦时,输入的文本正确显示,但是当我使用此组件关闭对话框窗口并重新打开,出现一些奇怪的行为,文本覆盖占位符文本。

看起来像这样:

当我最初输入文字时:

这是我的这个组件的代码:

const SERIES_MASK = [/\d/, /\d/, " ", /\d/, /\d/];

const useStyles = makeStyles({
  inputLabel: {
   margin: "-8px 0 0 14px",
  },
});

const SeriesMask: FC<{}> = (props) => <MaskedInput {...props} mask={SERIES_MASK} />;

export const DocumentSeriesField: FC<{
   name: string;
   value: string;
   label: string;
   error?: string;
   onChange: (e: React.ChangeEvent<HTMLInputElement>) => void;
   onBlur: (e: React.FocusEvent<HTMLInputElement>) => void;
   }> = ({ name, value, label, error, onChange, onBlur }) => {
      const classes = useStyles();
      const id = useMemo(() => randomId("series"), []);

      return (
       <FormControl>
         <InputLabel htmlFor={id} error={Boolean(error)} classes={{ root: classes.inputLabel }}>
          {label}
         </InputLabel>
         <OutlinedInput id={id} name={name} value={value} label={label} inputComponent={SeriesMask} error={Boolean(error)} onChange={onChange} onBlur={onBlur} />
         <FormHelperText error={Boolean(error)}>{error}</FormHelperText>
       </FormControl>
    );
};

您能否告诉我这里可能存在什么问题以及如何解决?

【问题讨论】:

  • useStyles 工作正常吗?重新打开对话框后,InputLabel 似乎没有任何样式
  • @UjinT34 是的,我认为是的。我刚刚从这个 sn-p 中删除了 useStyles 对象,但它看起来像这样: const useStyles = makeStyles({ inputLabel: { margin: "-8px 0 0 14px", }, });

标签: javascript reactjs material-ui frontend text-mask


【解决方案1】:

我认为您缺少 MaskedInput 中大纲输入的参考

尝试将inputRef传递给MaskedInput,标签应该能够发现字段已填充并返回到边框而不是覆盖。

系列掩码

interface SeriesMaskRefProps {
  inputRef: (ref: HTMLInputElement | null) => void;
} 

const SeriesMask: FC<{}> = (props: InputBaseComponentProps) => (
  <MaskedInput
    {...props}
    ref={(ref: any) => {
      (props as SeriesMaskRefProps).inputRef(ref ? ref.inputElement : null);
    }} // pass the ref to allow input label to connect with maaksed input
    mask={SERIES_MASK}
  />
);

【讨论】:

  • 谢谢!我在整个项目中应用了这些更改,并且效果很好。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-10
  • 1970-01-01
  • 1970-01-01
  • 2017-03-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多