在大多数情况下,我们推荐使用 受控组件 来处理表单数据。在一个受控组件中,表单数据是由 React 组件来管理的。
另一种替代方案是使用非受控组件,这时表单数据将交由 DOM 节点来处理。
受控组件
表单元素根据用户输入进行更新state状态
constructor(props) {
super(props);
this.state = {value: ''};
}
handleChange(event) {
this.setState({value: event.target.value});
}
handleSubmit(event) {
alert('提交的名字: ' + this.state.value);
event.preventDefault();// 阻止表单action默认提交
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
名字:
<input type="text" onChange={this.handleChange} value={this.state.value} />
</label>
<input type="submit" value="提交" />
</form>
);
}
表单元素上设置了 value 属性,因此显示的值将始终为 this.state.value,这使得 React 的 state 成为唯一数据源。
对于受控组件来说,输入的值始终由 React 的 state 驱动。
非受控组件
使用 ref 来从 DOM 节点中获取表单数据。
初始值
constructor(props) {
this.formRef = React.createRef<FormInstance>();
this.input = React.createRef<FormInstance>();
}
handleSubmit(e) {
alert('A name was submitted: ' + this.input.current.value);
event.preventDefault();
}
render() {
return (
<form ref={this.formRef}onSubmit={this.handleSubmit}>
<label>
Name:
<input type="text" ref={this.input} />
</label>
<input type="submit" value="Submit" />
</form>
);
}