受控组件:表单项输入数据能自动收集成状态。
非受控组件:需要时才手动读取表单输入框中的数据。
一、需求描述
收集输入的用户名和密码,并以弹框的方式显示出收集的用户名和密码。
二、代码实现
1. 通过非受控组件的方式实现
import React, {Component} from 'react';
class LoginForm extends Component {
constructor(props) {
super(props);
this.state = {}
this.handleForm = this.handleForm.bind(this)
}
handleForm(event) {
// 阻止事件的默认行为
event.preventDefault()
const name = this.nameInput.value
const pwd = this.pwdInput.value
alert(`提交表单的用户名为${name},密码为${pwd}`)
}
render() {
return (
<div>
{/*使用非受控组件的方式实现*/}
<form action="/login" onSubmit={this.handleForm}>
用户名:<input type="text" ref={input => this.nameInput = input}/>
密码:<input type="password" ref={input => this.pwdInput = input}/>
<button>提交</button>
</form>
</div>
);
}
}
export default LoginForm;
2. 通过受控组件的方式实现(官方推荐,但是本人觉得非受控组件的方式写法上更简单)
import React, {Component} from 'react';
class LoginForm extends Component {
constructor(props) {
super(props);
// 1. 初始化状态
this.state = {
name: "",
pwd: ""
}
this.handleForm = this.handleForm.bind(this)
this.handleName = this.handleName.bind(this)
this.handlePwd = this.handlePwd.bind(this)
}
handleForm(event) {
// 阻止事件的默认行为
event.preventDefault()
const {name} = this.state
const {pwd} = this.state
alert(`表单数据name:${name},pwd:${pwd}`)
}
handleName(event) {
// 2. 读取状态
const name = event.target.value
// 3. 更新状态
this.setState({name})
}
handlePwd(event) {
// 2. 读取状态
const pwd = event.target.value
// 3. 更新状态
this.setState({pwd})
}
render() {
return (
<div>
{/*使用受控组件的方式实现*/}
<form action="/login" onSubmit={this.handleForm}>
用户名:<input type="text" value={this.state.name} onChange={this.handleName}/>
密码:<input type="password" value={this.state.pwd} onChange={this.handlePwd}/>
<button>提交</button>
</form>
</div>
);
}
}
export default LoginForm;