gpt4 book ai didi

javascript - 如何从 Material UI 文本字段查看密码?

转载 作者:行者123 更新时间:2023-11-28 16:47:08 31 4
gpt4 key购买 nike

我的代码工作正常,当我在密码字段中写入时,文本被隐藏。有没有办法添加一个功能,让用户可以选择查看密码(如果他/她愿意)?

  const [email, setEmail] = useState('');
const [password, setPassword] = useState('');

return (
<div>
<div className='main-content'>
<form className="form" noValidate autoComplete="off">
{[{ label: "Email", state: email , type: "text", function: setEmail},
{ label: "Password", state: password , type: "password", function: setPassword},
].map((item, index) => (
<div>
<TextField
id="outlined-basic"
key={index}
label={item.label}
variant="outlined"
type= {item.type}
onChange= {e => item.function(e.target.value)}
/>
<br></br><br></br>
</div>
)
)}
</form>
</div>
</div>
);
}

最佳答案

您可以根据某些真/假状态更改值的类型。

// Add these variables to your component to track the state
const [showPassword, setShowPassword] = useState(false);
const handleClickShowPassword = () => setShowPassword(!showPassword);
const handleMouseDownPassword = () => setShowPassword(!showPassword);
// Then you can write your text field component like this to make the toggle work.
<TextField
label='Some label'
variant="outlined"
type={showPassword ? "text" : "password"} // <-- This is where the magic happens
onChange={someChangeHandler}
InputProps={{ // <-- This is where the toggle button is added.
endAdornment: (
<InputAdornment position="end">
<IconButton
aria-label="toggle password visibility"
onClick={handleClickShowPassword}
onMouseDown={handleMouseDownPassword}
>
{showPassword ? <Visibility /> : <VisibilityOff />}
</IconButton>
</InputAdornment>
)
}}
/>

在您的示例中,您使用循环来遍历您的字段。用我的示例替换您的文本字段会将切换添加到所有字段。这(可能)不是您想要的,因此您必须找到一种不同的方式来呈现这些字段。

<小时/>
// Required imports from the example.
import { TextField, InputAdornment, IconButton } from "@material-ui/core";
import Visibility from "@material-ui/icons/Visibility";
import VisibilityOff from "@material-ui/icons/VisibilityOff";

关于javascript - 如何从 Material UI 文本字段查看密码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60391113/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com