You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现MUI Input密码输入框仅接受数值且切换时保持数字类型

解决方案

针对你的三个需求,这里给出修改后的代码,同时解决原代码中的状态同步与输入限制问题:

修改后的代码

import React from 'react';
import { IconButton, InputAdornment, Input } from '@mui/material';
import Visibility from '@mui/icons-material/Visibility';
import VisibilityOff from '@mui/icons-material/VisibilityOff';
import { useDispatch, useSelector } from 'react-redux';
import { registerPin } from '../../../redux/passwordSlice';

const SSN = () => {
    const dispatch = useDispatch();
    const { pin } = useSelector((state) => state.inputValue);
    const [showPassword, setShowPassword] = React.useState(false);

    // 过滤非数字输入,确保仅接受数值
    const handleChange = (event) => {
        const numericValue = event.target.value.replace(/[^0-9]/g, '');
        dispatch(registerPin(numericValue));
    };

    const handleClickShowPassword = () => setShowPassword(!showPassword);

    return (
        <>
            <Input
                // 可见时用number类型,隐藏时用text类型配合样式模拟密码隐藏
                type={showPassword ? 'number' : 'text'}
                value={pin}
                onChange={handleChange}
                // 配置输入属性确保数字输入体验与限制
                inputProps={{
                    inputMode: 'numeric',
                    pattern: '[0-9]*',
                    // 隐藏状态下添加密码样式
                    style: showPassword ? {} : {
                        WebkitTextSecurity: 'disc',
                        textSecurity: 'disc'
                    }
                }}
                endAdornment={
                    <InputAdornment position='end'>
                        <IconButton
                            onClick={handleClickShowPassword}
                            edge='end'
                        >
                            {showPassword ? <VisibilityOff /> : <Visibility />}
                        </IconButton>
                    </InputAdornment>
                }
            />
        </>
    );
};

export default SSN;

关键改动说明

  • 仅接受数值输入:

    • 在handleChange中用正则/[^0-9]/g过滤非数字字符,保证redux存储的只有有效数值。
    • 添加inputProps的inputMode="numeric"(移动端弹出数字键盘)和pattern="[0-9]*"(桌面端输入验证),优化输入体验。
  • 切换密码可见/隐藏状态:

    • 移除冗余的本地password状态,直接复用redux中的pin作为输入框值,避免状态不同步问题。
    • 隐藏状态不再使用原生password类型,改用text类型配合WebkitTextSecurity: 'disc'样式模拟密码隐藏,既保留数字输入限制,又实现隐藏效果。
  • 保持两种状态的数字属性:

    • 可见状态用number类型,依赖原生数字输入限制;隐藏状态保留inputMode和pattern属性,同时通过样式隐藏文本,输入逻辑仍保持数字过滤,确保两种状态下都只能输入数字。

内容的提问来源于stack exchange,提问作者Clinto Abraham

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 09:50:26