ReactJS 如何生成随机密码

ReactJS 如何生成随机密码

在本文中,我们将指导您如何使用React构建随机密码生成器。

我们将使用Math.random()和Math.floor()方法生成随机字符。

先决条件

  • React简介
  • React状态
  • React事件
  • JSX语法

创建React应用的步骤

步骤1: 使用以下命令创建一个React应用

npx create-react-app random-password-generator

步骤2: 创建项目文件夹后,例如react-project,使用以下命令导航到该文件夹:

cd random-password-generator

项目结构

ReactJS 如何生成随机密码

方法

  • 该应用程序依赖于React的useState hook来管理各种状态变量,如passwordpasswordLengthuseSymbolsuseNumbersuseLowerCaseuseUpperCasesuccessMessage。当这些值改变时,这些变量负责触发UI的更新。
  • 为了生成一个随机密码,该应用程序利用generatePassword函数。该函数根据用户的偏好,通过遍历选定的字符集构造密码。为了方便复制密码,该应用程序包含了copyToClipboard功能。这个功能使用一个临时的文本框元素,在成功复制密码后向用户提供成功消息。
  • 通过用户界面中使用的内联CSS来实现视觉上的吸引力。像containerStyleinputContainerStylebuttonStyle这样的JavaScript对象定义了这些特定的样式,确保了一致的布局。总体而言,这个应用程序是React多用途hook useState以及内联CSS样式如何共同用于创建安全和用户友好的随机密码生成器的一个很好的示例。

示例:

// App.js 
import React, { useState } from "react"; 
  
const containerStyle = { 
    maxWidth: "400px", 
    margin: "1rem", 
    padding: "20px", 
    border: "1px solid #ccc", 
    borderRadius: "8px", 
    boxShadow: "0px 0px 10px 0px grey", 
}; 
  
const inputContainerStyle = { 
    display: "flex", 
    alignItems: "center", 
    marginBottom: "10px", 
}; 
  
const labelStyle = { 
    flex: "1", 
}; 
  
const inputStyle = { 
    padding: "5px", 
    border: "1px solid #ccc", 
    borderRadius: "3px", 
}; 
  
const checkboxContainerStyle = { 
    display: "flex", 
    alignItems: "center", 
    marginBottom: "5px", 
}; 
  
const buttonStyle = { 
    padding: "10px 15px", 
    backgroundColor: "#007bff", 
    color: "#fff", 
    border: "none", 
    borderRadius: "5px", 
    cursor: "pointer", 
    transition: "background-color 0.2s ease-in-out", 
}; 
  
const copyButtonStyle = { 
    marginLeft: "10px", 
}; 
  
const App = () => { 
    const [password, setPassword] = useState(""); 
    const [passwordLength, setPasswordLength] = 
        useState(12); 
    const [useSymbols, setUseSymbols] = useState(true); 
    const [useNumbers, setUseNumbers] = useState(true); 
    const [useLowerCase, setUseLowerCase] = useState(true); 
    const [useUpperCase, setUseUpperCase] = useState(true); 
    const [successMessage, setSuccessMessage] = 
        useState(""); 
  
    const generatePassword = () => { 
        let charset = ""; 
        let newPassword = ""; 
  
        if (useSymbols) charset += "!@#$%^&*()"; 
        if (useNumbers) charset += "0123456789"; 
        if (useLowerCase) 
            charset += "abcdefghijklmnopqrstuvwxyz"; 
        if (useUpperCase) 
            charset += "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; 
  
        for (let i = 0; i < passwordLength; i++) { 
            newPassword += charset.charAt( 
                Math.floor(Math.random() * charset.length) 
            ); 
        } 
  
        setPassword(newPassword); 
    }; 
  
    const copyToClipboard = () => { 
        const el = document.createElement("textarea"); 
        el.value = password; 
        document.body.appendChild(el); 
        el.select(); 
        document.execCommand("copy"); 
        document.body.removeChild(el); 
        setSuccessMessage("Password copied to clipboard!"); 
        setTimeout(() => setSuccessMessage(""), 2000);  
        // Hide message after 2 seconds 
    }; 
  
    return ( 
        <div style={containerStyle}> 
            <h1 
                style={{ 
                    color: "green", 
                    textAlign: "center", 
                }} 
            > 
                Geeksforgeeks 
            </h1> 
            <h3 style={{ textAlign: "center" }}> 
                Random Password Generator 
            </h3> 
            <div style={inputContainerStyle}> 
                <label style={labelStyle}> 
                    Password Length: 
                </label> 
                <input 
                    type="number"
                    min="8"
                    max="32"
                    value={passwordLength} 
                    onChange={(e) => 
                        setPasswordLength(e.target.value) 
                    } 
                    style={inputStyle} 
                /> 
            </div> 
            <div style={checkboxContainerStyle}> 
                <label> 
                    <input 
                        type="checkbox"
                        checked={useSymbols} 
                        onChange={() => 
                            setUseSymbols(!useSymbols) 
                        } 
                    /> 
                    Symbols 
                </label> 
                <label> 
                    <input 
                        type="checkbox"
                        checked={useNumbers} 
                        onChange={() => 
                            setUseNumbers(!useNumbers) 
                        } 
                    /> 
                    Numbers 
                </label> 
                <label> 
                    <input 
                        type="checkbox"
                        checked={useLowerCase} 
                        onChange={() => 
                            setUseLowerCase(!useLowerCase) 
                        } 
                    /> 
                    LowerCase 
                </label> 
                <label> 
                    <input 
                        type="checkbox"
                        checked={useUpperCase} 
                        onChange={() => 
                            setUseUpperCase(!useUpperCase) 
                        } 
                    /> 
                    UpperCase 
                </label> 
            </div> 
            <button 
                style={buttonStyle} 
                onClick={generatePassword} 
            > 
                Generate Password 
            </button> 
            {password && ( 
                <div style={inputContainerStyle}> 
                    <label style={labelStyle}> 
                        Generated Password: 
                    </label> 
                    <input 
                        type="text"
                        value={password} 
                        readOnly 
                        style={inputStyle} 
                    /> 
                    <button 
                        style={{ 
                            ...buttonStyle, 
                            ...copyButtonStyle, 
                        }} 
                        onClick={copyToClipboard} 
                    > 
                        Copy 
                    </button> 
                </div> 
            )} 
            {successMessage && ( 
                <p 
                    style={{ 
                        color: "green", 
                        textAlign: "center", 
                    }} 
                > 
                    {successMessage} 
                </p> 
            )} 
        </div> 
    ); 
}; 
  
export default App;

步骤4: 打开终端并输入下面提到的命令来打开程序。

npm start

输出

ReactJS 如何生成随机密码

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程