Material-UI中的遮罩文字栏位元件

Edu*_*ima 4 javascript frontend reactjs material-ui

我正在尝试在TextField组件中应用蒙版,但即时通讯没有成功。

我已经尝试过此解决方案,但是没有用。我尝试了所有方法,但似乎不再起作用。

我试图按照文档中的说明进行操作,但它们使用了Input组件,而该组件破坏了我的设计。

有人知道屏蔽TextField组件的方法吗?我正在使用material-ui 1.0.0-beta.24

Jul*_*ont 7

用于InputProps直接在TextField组件上设置遮罩。例如,假设所需的蒙版由该TextMaskCustom组件表示。然后,而不是把它应用到Input直接,你可以将其应用到你TextField使用InputProps像这样:

<TextField
  id="maskExample"
  label="Mask Example"
  className={classes.textField}
  margin="normal"
  InputProps={{
    inputComponent: TextMaskCustom,
    value: this.state.textmask,
    onChange: this.handleChange('textmask'),
  }}
/>
Run Code Online (Sandbox Code Playgroud)

之所以有效,TextField是因为a 实际上是组件周围的包装器Input(其中混入了其他一些东西)。的InputProps的道具TextField让你进入内部Input,这样你就可以设置屏蔽这种方式,同时保留的造型TextField组成部分。

这是一个完整的工作示例,改编自docs中演示

import React from 'react';
import MaskedInput from 'react-text-mask';
import PropTypes from 'prop-types';
import { withStyles } from 'material-ui/styles';
import TextField from 'material-ui/TextField';

const styles = theme => ({
  container: {
    display: 'flex',
    flexWrap: 'wrap',
  },
  input: {
    margin: theme.spacing.unit,
  },
});

const TextMaskCustom = (props) => {
  const { inputRef, ...other } = props;

  return (
    <MaskedInput
      {...other}
      ref={inputRef}
      mask={['(', /[1-9]/, /\d/, /\d/, ')', ' ', /\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/]}
      placeholderChar={'\u2000'}
      showMask
    />
  );
}

TextMaskCustom.propTypes = {
  inputRef: PropTypes.func.isRequired,
};

class FormattedInputs extends React.Component {
  state = {
    textmask: '(1??) ???-????',
  };

  handleChange = name => event => {
    this.setState({
      [name]: event.target.value,
    });
  };

  render() {
    const { classes } = this.props;
    return (
      <div className={classes.container}>
        <TextField
          id="maskExample"
          label="Mask Example"
          className={classes.textField}
          margin="normal"
          InputProps={{
            inputComponent: TextMaskCustom,
            value:this.state.textmask,
            onChange: this.handleChange('textmask'),
          }}
        />
      </div>
    );
  }
}

FormattedInputs.propTypes = {
  classes: PropTypes.object.isRequired,
};

export default withStyles(styles)(FormattedInputs);
Run Code Online (Sandbox Code Playgroud)

  • 如果您使用的是较新的 Material UI(使用“@material-ui/core”导入),那么您将收到此错误:“Material-UI:您向输入组件提供了一个‘inputComponent’,该组件无法正确处理`inputRef` 属性。确保使用 HTMLInputElement 调用 `inputRef` 属性。”要解决此问题,请将 `TextMaskCustom` 中的 `ref=` 行更改为: ```ref={ref =&gt; { inputRef(ref ? ref.inputElement : null); }}``` (5认同)