1.引入from组件
import {Form} from "antd";
2.在组件上方使用@Form.create()注解注入表单,注入后可以通过this.props.form获取
@Form.create()
export default class CountPageextends Component{
....
}
3.通过const {getFieldDecorator} = this.props.form; 获取表单的双向绑定函数
<Form>
<Card title={"基本信息"}>
<Row gutter={24}>
<Col span={8} offset={4}>
<Form.Item label={"通票首重重量"}>
{getFieldDecorator('firstWeight')(<Input placeholder={"首重重量KG"}/>)}
</Form.Item>
</Col>
<Col span={8}>
<Form.Item label={"通票首重价格"}>
{getFieldDecorator('firstWeightPrice')(<Input placeholder={"首重价格(元)"}/>)}
</Form.Item>
</Col>
</Row>
</Card>
4.编写函数获得表单内的值
submit = ()=>{
const data =this.props.form.getFieldsValue();
console.log("表单中的值",data)
}
补充:
1.
报`getFieldDecorator` will override `value`, so please don't set `value` directly and use `setFieldsValue` to set it.错误的话,因为getFieldDecorator可以设置默认值,会替换input的默认值。
{getFieldDecorator('xxx',{initialValue:1})(<Input placeholder={"首重重量KG"}/>)}
解决
2.双向绑定过程中对表单内容校验
<Form.Item label="" style={{marginBottom:0}}>
{getFieldDecorator('select_tas', {
rules: [{required:true,message:DEFAULT_TIMEAREA[1] }],
initialValue:DEFAULT_TIMEAREA[0]
})(
<Select id={"tas"} style={{width:'100%' }}>
{timeArea ?timeArea.map(({ value, text }) =><Option key={'time' + value} value={value}>{text}</Option>) :null}
</Select>
)}
</Form.Item>
3.表单内容改变时动态更新
@Form.create({onValuesChange:(props, changedValues, allValues) => {that.requestData(props, changedValues, allValues)}})
class SelectBarextends Component{
...
//选中时调用提交表单
requestData = (props, changedValues, allValues) =>{
}
}