如何在Material-UI Autocomplete组件中集成Number Mask实现手机号格式转换
实现方案
你需要把react-number-format封装为适配MUI TextField的自定义输入组件,再替换Autocomplete的renderInput中的输入逻辑即可,具体实现如下:
步骤1:封装自定义NumberFormat输入组件
先把NumberFormat包装成符合MUI TextField inputComponent要求的组件,同时修正你原写法里的属性拼写错误:formate应为format
import NumberFormat from 'react-number-format'; const NumberFormatCustom = (props) => { const { inputRef, onChange, ...other } = props; return ( <NumberFormat {...other} getInputRef={inputRef} onValueChange={(values) => { onChange({ target: { name: props.name, value: values.value, // 可直接拿到纯数字值,也可以替换为formattedValue取带格式的内容 }, }); }} format="(###)-###-####" mask="_" prefix="01" /> ); };
步骤2:修改Autocomplete组件配置
需要适配两个核心逻辑:1)renderInput中指定TextField的inputComponent为我们封装的组件;2)调整搜索匹配规则,避免格式符号影响搜索结果
import { Autocomplete, TextField, createFilterOptions } from '@material-ui/lab'; // 自定义搜索过滤逻辑:忽略括号、横杠等格式符号,只用纯数字做匹配 const filterOptions = createFilterOptions({ matchFrom: 'any', stringify: (option) => option.phone.replace(/\D/g, ''), // 把选项里的手机号转为纯数字再匹配 }); <Autocomplete id="combo-box-demo" options={你的手机号选项数组} // 替换为你自己的选项数据源 filterOptions={filterOptions} getOptionLabel={(option) => { // 选项展示统一用相同格式,保持视觉一致性 return option.phone.replace(/(\d{3})(\d{3})(\d{4})/, '($1)-$2-$3'); }} style={{ width: 300 }} classes={{ option: classes.option }} renderInput={(params) => ( <TextField {...params} label="手机号搜索" variant="outlined" InputProps={{ ...params.InputProps, inputComponent: NumberFormatCustom, // 绑定自定义格式输入组件 }} /> )} />
关键注意点
- 表单提交时如果需要纯数字手机号,直接取Autocomplete绑定的value即可,封装组件已经把纯数字值透传给了onChange
- 如果不需要
prefix="01"前缀可以直接删除该属性,格式会严格按照(###)-###-####展示 - 输入时会自动过滤非数字字符,用户输入纯数字
1234567899会自动转换为(123)-456-7899格式
内容的提问来源于stack exchange,提问作者Alexei Ryan
相关产品推荐
相关产品推荐

