用React Hook写一个简单的登录表单示例,两种方式:
第一种:
import React, { useState } from "react";
import ReactDOM from "react-dom";
function LoginForm() {
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const printValues = e => {
e.preventDefault();
console.log(username, password);
};
return (
<form onSubmit={printValues}>
<label>
Username:
<input
value={username}
onChange={event => setUsername(event.target.value)}
name="username"
type="text"
/>
</label>
<br />
<label>
Password:
<input
value={password}
onChange={event => setPassword(event.target.value)}
name="password"
type="password"
/>
</label>
<br />
<button>Submit</button>
</form>
);
}
ReactDOM.render(<LoginForm />, document.getElementById("container"));
第二种:
这里的setState函数只是一个更新函数的名字,所以随你心意,不一定叫setState
import React, { useState } from "react";
import ReactDOM from "react-dom";
function LoginForm() {
const [form, setState] = useState({
username: "",
password: ""
});
const printValues = e => {
e.preventDefault();
console.log(form.username, form.password);
};
const updateField = e => {
setState({
...form,
[e.target.name]: e.target.value
});
};
return (
<form onSubmit={printValues}>
<label>
Username:
<input value={form.username} name="username" onChange={updateField} />
</label>
<br />
<label>
Password:
<input
value={form.password}
name="password"
type="password"
onChange={updateField}
/>
</label>
<br />
<button>Submit</button>
</form>
);
}
ReactDOM.render(<LoginForm />, document.getElementById("container"));