【问题标题】:How to hide/unhide password Material uI如何隐藏/取消隐藏密码 Material ui
【发布时间】:2021-11-15 05:02:06
【问题描述】:
我在我的应用中有一个登录名,我希望可以选择隐藏和取消隐藏密码。
这是我的文本字段:
<TextField
className={classes.textf}
variant="standard"
placeholder="password"
onChange={(password) => setPassword(password)}
/>
【问题讨论】:
标签:
reactjs
react-native
material-ui
【解决方案1】:
TextField component has a type prop,您可以将其设置为“文本”或“密码”以显示/隐藏值。
const [showPassword, setShowPassword] = useState(false);
// ...
<TextField
type={showPassword ? "text" : "password"}
placeholder="password"
/>
<button onClick={() => setShowPassword(s => !s)}>Toggle visibility</button>
【解决方案2】:
这可能会解决您的问题,
import * as React from 'react';
import IconButton from '@mui/material/IconButton';
import FilledInput from '@mui/material/FilledInput';
import InputLabel from '@mui/material/InputLabel';
import InputAdornment from '@mui/material/InputAdornment';
import FormControl from '@mui/material/FormControl';
import Visibility from '@mui/icons-material/Visibility';
import VisibilityOff from '@mui/icons-material/VisibilityOff';
export default function InputAdornments() {
const [values, setValues] = React.useState({
password: '',
showPassword: false,
});
const handleChange = (prop) => (event) => {
setValues({ ...values, [prop]: event.target.value });
};
const handleClickShowPassword = () => {
setValues({
...values,
showPassword: !values.showPassword,
});
};
const handleMouseDownPassword = (event) => {
event.preventDefault();
};
return (
<div>
<FormControl sx={{ m: 1, width: '25ch' }} variant="filled">
<InputLabel
htmlFor="filled-adornment-
password">
Password
</InputLabel>
<FilledInput
id="filled-adornment-password"
type={values.showPassword ? 'text' : 'password'}
value={values.password}
onChange={handleChange('password')}
endAdornment={
<InputAdornment position="end">
<IconButton
aria-label="toggle password visibility"
onClick={handleClickShowPassword}
onMouseDown={handleMouseDownPassword}
edge="end">
{values.showPassword ? <VisibilityOff /> : <Visibility />}
</IconButton>
</InputAdornment>
}
/>
</FormControl>
</div>
);
}