下面是一个没有钩子的登录组件。该组件具有两个输入字段和一个提交按钮。我们如何修改此组件使用钩子并将此组件转换为可以使用状态的功能组件?
import React from 'react';
import { userService } from '../services/user.services';
class Login extends React.Component {
constructor(props) {
super(props);
this.state = {
username: '',
password: '',
submitted: false,
loading: false,
error: ''
}
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit(e) {
e.preventDefault();
this.setState({ submitted: true });
const data = this.state;
userService.login(data.username, data.password)
.then(
user => {
const { from } = this.props.location.state || { from: { pathname: "/" } };
this.props.history.push(from);
}
);
}
handleChange(e) {
const { name, value } = e.target;
this.setState({ [name]: value });
}
render() {
const { ...data } = this.state;
return (
<div className="login-box">
<h1>Travel With Us</h1>
<form onSubmit={this.handleSubmit}>
<div className="text-box">
<i className="fa fa-user"></i>
<input type="text" name="username" defaultValue={data.username} onChange={this.handleChange} placeholder="Username" />
</div>
<div className="text-box">
<i className="fa fa-lock" />
<input type="password" name="password" defaultValue={data.password} onChange={this.handleChange} placeholder="Passward" />
</div>
<button className="btn" value="login">Sign in</button>
</form>
</div>
);
}
}
export default Login;
以下是我转换为使用钩子的示例代码。
import React, { useState } from 'react';
import { userService } from '../services/user.services';
const LoginHooks = (props) => {
const [username, setUsername] = useState("");
const [password, setPassword] = useState("");
const [submitted, setSubmit] = useState(false);
let handleSubmit = function (e) {
e.preventDefault();
console.log(submitted);
setSubmit(true);
userService.login(username, password)
.then(
user => console.log(user)
);
};
return (
<div className="login-box">
<h1>Login</h1>
<form onSubmit={handleSubmit}>
<div className="text-box">
<i className="fa fa-user"></i>
<input type="text" name="username" defaultValue={username} onChange={({target}) => setUsername(target.value)} placeholder="Username" />
</div>
<div className="text-box">
<i className="fa fa-lock" />
<input type="password" name="password" defaultValue={password} onChange={({target}) => setPassword(target.value)} placeholder="Passward" />
</div>
<button className="btn" value="login">Sign in</button>
</form>
</div>
);
}
export default LoginHooks;