如何在React Material UI的TextField密码输入框内放置眼睛图标?
问题原因与修正方案
你代码里存在3处配置错误,修改后即可正常在密码输入框右侧显示切换可见性的眼睛图标:
- 错误1:
endAdornment对应的InputAdornment不应设置position="start",要改为position="end"才会显示在输入框右侧 - 错误2:
InputAdornment的classes属性传入值格式错误,直接用style调整边距即可 - 错误3:
inputProps中设置的width: "100%"会挤压图标显示空间,需要删除该属性
修正后的完整代码如下:
import { Visibility, VisibilityOff } from '@mui/icons-material'; import { TextField, InputAdornment, IconButton } from '@mui/material'; import { useState } from 'react'; // 组件内逻辑 const [showPassword, setShowPassword] = useState(false); const handleClickShowPassword = () => setShowPassword((prev) => !prev); const handleMouseDownPassword = (event) => { event.preventDefault(); }; // 渲染的TextField组件 <TextField variant="outlined" margin="dense" required fullWidth placeholder={placeholder} name={label} type={showPassword ? "text" : type} id={id} inputProps={{ style: { background: "white", boxShadow: "rgba(0, 0, 0, 0.24) 0px 3px 8px", height: "15px", borderRadius: "10px", marginRight: 0, }, }} InputProps={{ classes: { notchedOutline: classes.noBorder }, endAdornment: type === "password" ? ( <InputAdornment position="end" style={{ marginRight: '8px' }} > <IconButton onClick={handleClickShowPassword} onMouseDown={handleMouseDownPassword} edge="end" > {showPassword ? <Visibility /> : <VisibilityOff />} </IconButton> </InputAdornment> ) : null, }} />
内容的提问来源于stack exchange,提问作者Sachindu Himash
相关产品推荐
相关产品推荐

