用react 写一个用户登录案例
时间: 2024-05-10 19:20:15 浏览: 9
以下是一个使用React编写的用户登录示例:
首先,我们需要编写一个登录组件:
```jsx
import React, { useState } from 'react';
import { useHistory } from 'react-router-dom';
const Login = () => {
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const [error, setError] = useState('');
const history = useHistory();
const handleLogin = (e) => {
e.preventDefault();
// Check login credentials
if (username === 'admin' && password === 'password') {
// Redirect to dashboard page
history.push('/dashboard');
} else {
setError('Invalid username or password');
}
};
return (
<div>
<h1>Login</h1>
{error && <p>{error}</p>}
<form onSubmit={handleLogin}>
<div>
<label htmlFor="username">Username:</label>
<input
type="text"
id="username"
value={username}
onChange={(e) => setUsername(e.target.value)}
/>
</div>
<div>
<label htmlFor="password">Password:</label>
<input
type="password"
id="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
</div>
<button type="submit">Login</button>
</form>
</div>
);
};
export default Login;
```
在此示例中,我们使用useState钩子来跟踪输入字段的值,并使用useHistory钩子将用户重定向到仪表板页面。我们还检查登录凭据是否正确,并在失败的情况下设置错误消息。
接下来,我们需要在App.js中设置路由器和路径,以便在需要时将用户重定向到登录页面或仪表板页面:
```jsx
import React from 'react';
import { BrowserRouter as Router, Switch, Route } from 'react-router-dom';
import Login from './Login';
import Dashboard from './Dashboard';
const App = () => {
return (
<Router>
<Switch>
<Route exact path="/">
<Login />
</Route>
<Route path="/dashboard">
<Dashboard />
</Route>
</Switch>
</Router>
);
};
export default App;
```
在此示例中,我们将Login组件与路径“/”相关联,将Dashboard组件与路径“/dashboard”相关联。通过这些设置,我们可以确保用户在访问仪表板页面之前必须先进行身份验证。
最后,我们需要编写一个仪表板组件,以便在成功登录后向用户显示:
```jsx
import React from 'react';
const Dashboard = () => {
return (
<div>
<h1>Dashboard</h1>
<p>You are now logged in!</p>
</div>
);
};
export default Dashboard;
```
这是一个基本的React用户登录示例,您可以根据需要将其扩展并添加更多功能。