javascript
复制代码
import React, { PureComponent, createRef } from "react";
export class app extends PureComponent {
constructor() {
super();
this.state = {
username: "",
password: "",
isAgree: false,
hobbies: [
{ value: "sing", text: "唱", isChecked: false },
{ value: "dance", text: "跳", isChecked: false },
{ value: "rap", text: "Rap", isChecked: false },
],
answer: ["A"],
intro: "outman",
};
this.introRef = createRef();
}
componentDidMount() {
// this.introRef.current.addEventListener
}
handleSubmitClick(event) {
// 1.阻止默认行为
event.preventDefault();
// 2.获取到所有的表单数据,对数据进行组建
console.log(this.state.username);
console.log(this.state.password);
console.log(
this.state.hobbies
.filter((item) => item.isChecked)
.map((item) => item.value)
);
console.log(this.state.answer);
console.log(this.introRef.current.value);
// 3.以网络请求的方式将数据传递给服务器(ajax/fetch/axios)
}
handleUserDataChange(event) {
const keyName = event.target.name;
this.setState({
[keyName]: event.target.value,
});
}
handleAgreeChange(event) {
this.setState({
isAgree: event.target.checked,
});
}
handleHobbiesChange(event, index) {
const hobbies = [...this.state.hobbies];
hobbies[index].isChecked = event.target.checked;
this.setState({
hobbies,
});
}
handleAnswerChange(event) {
const options = Array.from(event.target.selectedOptions);
const values = options.map((item) => item.value);
this.setState({
answer: values,
});
}
render() {
const { username, password, isAgree, hobbies, answer, intro } = this.state;
return (
<div>
<form onSubmit={(e) => this.handleSubmitClick(e)}>
{/* 1.用户名和密码 */}
<div>
<label htmlFor="username">
用户:
<input
id="username"
type="text"
name="username"
value={username}
onChange={(e) => this.handleUserDataChange(e)}
/>
</label>
<label htmlFor="password">
密码:
<input
id="password"
type="password"
name="password"
value={password}
onChange={(e) => this.handleUserDataChange(e)}
/>
</label>
</div>
{/* 2.checkbox */}
<label htmlFor="agree">
<input
id="agree"
type="checkbox"
checked={isAgree}
onChange={(e) => this.handleAgreeChange(e)}
/>
同意协议
</label>
{/* 3.checkbox多选 */}
<div>
您的爱好:
{hobbies.map((item, index) => {
return (
<label htmlFor={item.vlaue} key={item.value}>
<input
type="checkbox"
id={item.vlaue}
checked={item.isChecked}
onChange={(e) => this.handleHobbiesChange(e, index)}
/>
{item.text}
</label>
);
})}
</div>
{/* 4.select */}
<select
value={answer}
multiple
onChange={(e) => this.handleAnswerChange(e)}
>
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="D">D</option>
</select>
{/* 5.非受控组件 */}
<input type="text" defaultValue={intro} ref={this.introRef} />
<div>
<button type="submit">注册</button>
</div>
</form>
</div>
);
}
}
export default app;