表单允许用户与应用程序交互以及从用户那里收集信息。表单可以执行许多任务,例如用户身份验证、添加用户、搜索、过滤等。表单可以包含文本字段、按钮、复选框、单选按钮等。
React 提供了一种有状态的、反应式的方法来构建表单。React 中的表单类似于 HTML 表单。但在 React 中,组件的 state
属性仅通过 setState()
更新,并由 JavaScript 函数处理它们的提交。此功能可以完全访问用户在表单中输入的数据。
import React, { Component } from 'react';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {value: ''};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
this.setState({value: event.target.value});
}
handleSubmit(event) {
alert('You have submitted the input successfully: ' + this.state.value);
event.preventDefault();
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<h1>Controlled Form Example</h1>
<label>
Name:
<input type="text" value={this.state.value} onChange={this.handleChange} />
</label>
<input type="submit" value="Submit" />
</form>
);
}
}
export default App;