我试图在TextField组件中应用掩码,但是一直没有成功。
我已经尝试了这个解决方案,但没有起作用。 我试过各种方法,但好像都不再起作用了。
我尝试按照文档中给出的说明,但它们使用Input组件,而这个组件破坏了我的设计。
有人知道如何掩盖TextField组件吗? 我正在使用material-ui 1.0.0-beta.24
我试图在TextField组件中应用掩码,但是一直没有成功。
我已经尝试了这个解决方案,但没有起作用。 我试过各种方法,但好像都不再起作用了。
我尝试按照文档中给出的说明,但它们使用Input组件,而这个组件破坏了我的设计。
有人知道如何掩盖TextField组件吗? 我正在使用material-ui 1.0.0-beta.24
使用 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
实际上是一个围绕着 Input
组件的包装器 (其中还有其他一些混合内容)。TextField
的 InputProps
属性可以让您访问内部的 Input
,从而在保留 TextField
样式的同时设置掩码方式。
以下是一个完整的工作示例,改编自文档中的 演示:
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);
InputProps={{
inputComponent: TextMaskCustom,
inputProps: {...}
}}
添加(小写)inputProps 可以让您传递用于输入组件的 props。 - Nate-inputComponent
。
请确保使用 HTMLInputElement 调用 inputRef
属性。"为了解决这个问题,将 TextMaskCustom
中的 ref=
行更改为以下内容:ref={ref => {
inputRef(ref ? ref.inputElement : null);
}}
- jon1467
Input
组件是如何破坏你的设计的? - Jules Dupont