通常情况下建议使用控件controlled component管理forms
数据,在控件
中表单数据受控于React component
,也就是实时通过监控onChange时间修改state
。相反的,Uncontrolled Components
中表单数据受DOM自己控制
以下uncontrolled component
示例,借助ref
获取DOM值,避免了在input
中写监听事件了
class NameForm extends React.Component {
constructor(props) {
super(props);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit(event) {
alert('A name was submitted: ' + this.input.value);
event.preventDefault();
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
Name:
<input type="text" ref={(input) => this.input = input} />
</label>
<input type="submit" value="Submit" />
</form>
);
}
}
这样代码会简洁,比较简单的表单使用这种形式会更快捷点,React
文档对它的形容是It can also be slightly less code if you want to be quick and dirty.
React
渲染周期中value
属性会覆盖DOM中的值,表单默认值通过设置相应state
属性值展示
class NameForm extends React.Component {
constructor(props) {
super(props);
this.state = {value: ''};
}
render() {
return (
<form>
<label>
Name:
<input type="text" value={this.state.value} />
</label>
<input type="submit" value="Submit" />
</form>
);
}
}
uncontrolled component
如果想要设置默认值,用defaultValue
而不是value
,测试时使用value
,表单的数据将不能改变,也就是无法再输入了
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
Name:
<input
defaultValue="Bob"
type="text"
ref={(input) => this.input = input} />
</label>
<input type="submit" value="Submit" />
</form>
);
}
<input type="checkbox">
和<input type="radio">
支持defaultChecked
,<select>
和 <textarea>
支持 defaultValue