问题
属性,报错
useForm
is not connect to any Form element. Forget to pass form
prop?官网示例
简介:接收父元素传递过来的初始值、可显示、可使用父元素的更改
子组件modal+form(antd4modal+form只能以函数形式呈现,写法参考官网)
import React, { useState } from 'react';
import { Button, Modal, Form, Input, Radio } from 'antd';
const CollectionCreateForm = ({ visible, submitMap, onCancel, currentDetailData }) => {
const [form] = Form.useForm();
const layout = {
labelCol: { span: 5 },
wrapperCol: { span: 18 },
};
let initValues = currentDetailData == undefined || currentDetailData.length == 0 ? {} :
{
name:currentDetailData.name,
crs:currentDetailData.crs,
}
form.setFieldsValue(initValues)
return (
<Modal
visible={visible}
title="服务详情"
onCancel={onCancel}
width={800}
destroyOnClose={true}
onOk={() => {
form
.validateFields()
.then(values => {
form.resetFields();
form.setFieldsValue(values)
submitMap(values);
})
.catch(info => {
console.log('校验失败:', info);
});
}}
>
<Form
form={form}
{...layout}
name="serverDetail"
initialValues={initValues}
>
<Form.Item label="名称" name="name" >
<Input/>
</Form.Item>
<Form.Item label="坐标系信息" name="crs">
<Input disabled/>
</Form.Item>
</Form>
</Modal>
);
};
export default CollectionCreateForm;
父组件调用
import React from 'react';
import { Button, Modal, Form, Input, Radio } from 'antd';
import CollectionCreateForm from './ModalForm';
let data = [];// 总数据
class ModalFormPage extends React.Component{
constructor(props){
super(props)
this.state = {
visible:false,
currentDetailData:[] // 当前需要传递给子组件的数据,用于显示form表单初始值
}
}
componentDidMount(){
// 模拟接口值
data = [
{
name:'11111',
crs:'xxx:xxxx',
serviceType:'type',
dataType:'string',
serviceUrl:'/xxx/xxx/xxx',
},
{
name:'22222',
crs:'xxx:xxxx',
serviceType:'type',
dataType:'string',
serviceUrl:'/xxx/xxx/xxx',
},
{
name:'33333',
crs:'xxx:xxxx',
serviceType:'type',
dataType:'string',
serviceUrl:'/xxx/xxx/xxx',
}
]
}
// 数据修改
onCreate = values => {
console.log('form接收数据: ', values);
this.changeVisible(false);
};
// 弹框显示状态、及当前需要展示的数据赋值
changeVisible = (status,index) =>{
this.setState({
visible:status,
})
if(index != undefined){
this.setState({
currentDetailData:data[index]
})
}
}
render(){
return (
<div>
<div style={{padding:'20px'}}>
<Button
type="primary"
onClick={() => {
this.changeVisible(true,0);
}}
>
数据一
</Button>
<Button
type="primary"
onClick={() => {
this.changeVisible(true,1);
}}
>
数据二
</Button>
<Button
type="primary"
onClick={() => {
this.changeVisible(true,2);
}}
>
数据三
</Button>
</div>
<CollectionCreateForm
visible={this.state.visible}
submitMap={this.onCreate}
onCancel={() => {
this.changeVisible(false);
}}
currentDetailData={this.state.currentDetailData}
/>
</div>
);
}
}
export default ModalFormPage;