使用React.ts创建一个密码生成器的简单示例
import React, { useState } from 'react';
function PasswordGenerator() {
const [passwordLength, setPasswordLength] = useState(12);
const [password, setPassword] = useState('');
const generatePassword = () => {
const chars = 'abcdefghijklmnopqrstuvwxyz!@#$%^&*()ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';
let pass = '';
for (let i = 0; i < passwordLength; i++) {
const randomChar = chars[Math.floor(Math.random() * chars.length)];
pass += randomChar;
}
setPassword(pass);
};
return (
<div>
<button onClick={generatePassword}>Generate Password</button>
<input type="number" value={passwordLength} onChange={(e) => setPasswordLength(+e.target.value)} />
<p>Generated Password: <strong>{password}</strong></p>
</div>
);
}
export default PasswordGenerator;
这段代码实现了一个简单的密码生成器,用户点击按钮后会生成一个随机的密码,密码的长度可以通过输入框进行调整。这个例子展示了如何在React组件中使用hooks(useState)来管理状态,以及如何处理用户输入。
评论已关闭