react写一个登录页面
时间: 2024-06-13 22:07:52 浏览: 13
以下是一个简单的React登录页面的示例代码,其中使用了react-router-dom进行路由跳转和axios进行数据请求:
```jsx
import { useState } from 'react';import { useHistory } from 'react-router-dom';
import axios from 'axios';
function LoginPage() {
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const history = useHistory();
const handleLogin = async () => {
try {
const response = await axios.post('/api/login', { username, password });
if (response.data.success) {
// 登录成功,跳转到首页
history.push('/');
} else {
alert('登录失败,请检查用户名和密码');
}
} catch (error) {
console.error(error);
alert('登录失败,请稍后再试');
}
};
return (
<div>
<h1>登录页面</h1>
<div>
<label>用户名:</label>
<input type="text" value={username} onChange={(e) => setUsername(e.target.value)} />
</div>
<div>
<label>密码:</label>
<input type="password" value={password} onChange={(e) => setPassword(e.target.value)} />
</div>
<button onClick={handleLogin}>登录</button>
</div>
);
}
export default LoginPage;
```
在上面的代码中,我们首先引入了useState和useHistory两个React Hook,分别用于管理组件的状态和路由跳转。然后,我们定义了一个LoginPage组件,其中包含了一个表单,用于输入用户名和密码。当用户点击登录按钮时,我们使用axios库向后端发送POST请求,请求的数据为输入的用户名和密码。如果登录成功,我们使用useHistory Hook进行路由跳转,跳转到首页;否则,我们弹出一个提示框,提示用户登录失败。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)