收集表单数据
受控组件
在 HTML 中,表单元素(如input、 textarea 和 select)通常自己维护 state,并根据用户输入进行更新。而在 React 中,可变状态(mutable state)通常保存在组件的 state 属性中,并且只能通过使用 setState()来更新
通过event.target获取当前节点
// 随着输入,将数据存储在state中,然后从state中取数据
class Demo extends React.Component {
// 状态初始化
state = {
username: '',
password: ''
}
handleSubmit = (event) => {
event.preventDefault();// 阻止表单提交
const { username, password } = this.state;
console.log(username, password);
}
saveUsername = (event) => {
this.setState({ username: event.target.value });
}
savePwd = (event) => {
this.setState({ password: event.target.value })
}
render() {
return (
<form onSubmit={this.handleSubmit}>
用户名: <input type="text" onChange={this.saveUsername} name="username" />
密码: <input type="password" name="password" onChange={this.savePwd} />
<button>登录</button>
</form>
)
}
}
非受控组件
输入类DOM,现用现取,不通过state
// 输入类DOM,现用现取
class Demo extends React.Component {
handleSubmit = (event) => {
event.preventDefault();// 阻止表单提交
const { username, password } = this;
alert(`用户名: ${username.value} + 密码:${username.value}`);
}
render() {
return (
<form onSubmit={this.handleSubmit}>
用户名: <input type="text" name="username" ref={(c) => { this.username = c }} />
密码: <input type="password" name="password" ref={(c) => { this.password = c }} />
<button>登录</button>
</form>
)
}
}
标签:受控,username,React,state,组件,password,event
From: https://www.cnblogs.com/ucbb/p/17083755.html