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

新手上路,请多包涵

我的代码工作正常,当我在密码字段中写入时,文本被隐藏了。有什么方法可以添加功能,让用户可以根据需要选择查看密码?

   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>
        );
      }

原文由 x89 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 525
1 个回答

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

 // 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";

原文由 Jap Mul 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题