使用InputProps 直接在TextField 组件上设置掩码。例如,假设您想要的掩码由TextMaskCustom 组件表示。然后,您可以使用InputProps 将其应用于您的TextField,而不是直接将其应用于Input,如下所示:
<TextField
id="maskExample"
label="Mask Example"
className={classes.textField}
margin="normal"
InputProps={{
inputComponent: TextMaskCustom,
value: this.state.textmask,
onChange: this.handleChange('textmask'),
}}
/>
这是有效的,因为 TextField 实际上是 wrapper around an Input component(混入了其他一些东西)。 TextField 的 InputProps 属性使您可以访问内部 Input,因此您可以这样设置掩码,同时保留 TextField 组件的样式。
这是改编自 demos in the 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);