react实现动态增减表单项的示例代码
作者:做一个体面人
在做项目的时候,甲方给的信息有限,网页的备案信息写成固定的,之后验收的时候,甲方要求把这个备案信息写成动态的,可以自增减,下面通过实例代码给大家介绍react实现动态增减表单项的示例,感兴趣的朋友跟随小编一起看看吧
在做项目的时候,甲方给的信息有限,网页的备案信息写成固定的,如下图所示:
之后验收的时候,甲方要求把这个备案信息写成动态的,可以自增减,就去react组件库看看有没有具体的实现,果真有,具体实现如下:
import { PageHeaderWrapper } from '@ant-design/pro-layout'; import { Button, Form, Input, Card, Space, message} from 'antd'; import CustomForm from '@/components/Form'; import { FormattedMessage, useIntl } from 'umi'; import { saveRecordInfomation, getRecordInfomation } from '@/services/record' import { useEffect } from 'react'; import { MinusCircleOutlined, PlusOutlined } from '@ant-design/icons'; const formItemLayout = { labelCol: { xs: { span: 24, }, sm: { span: 6, }, }, wrapperCol: { xs: { span: 24, }, sm: { span: 14, }, }, }; const RecordInformation = () => { const intl = useIntl() const [form] = Form.useForm(); const onReset = () => { form.resetFields(); }; useEffect(() => { getRecordInfo() return () => { }; }, []); const getRecordInfo = async () => { getRecordInfomation().then((res) => { if (res.code === 0) { form.setFieldsValue({ recordsInformation: res.data.map((item, index) => ({ ...item, key: index, })), }); } }); } const onFinish = async (forms) => { const res = await saveRecordInfomation(forms.recordsInformation) if (res.code === 0) { message.success(intl.formatMessage({ id: 'pages.cms.save.success' })) getRecordInfo() } else { message.error(intl.formatMessage({ id: 'pages.cms.save.fail' })) } } return ( <PageHeaderWrapper ghost={false}> <div> <Card style={{ height: '95%', }}> <Form {...formItemLayout} variant="filled" style={{ maxWidth: 1000, }} form={form} onFinish={onFinish} > <Form.List name="recordsInformation"> {(fields, { add, remove }) => ( <> {fields.map(({ key, name, ...restField }) => ( <Space key={key} style={{ display: 'flex', marginBottom: 8, marginRight: 0, }} align="baseline" > <Form.Item {...restField} name={[name, 'label']} rules={[{ required: true, message: 'Missing first name' }]} > <Input placeholder={intl.formatMessage({ id: 'pages.record.info.content.public.net.example.filing'})} style={{ width:105, textAlign: 'right', border:'none' }} /> </Form.Item> <Form.Item {...restField} name={[name, 'value']} rules={[{ required: true, message: 'Missing last name' }]} > <Input placeholder={intl.formatMessage({ id: 'pages.record.info.content.public.net.example.filing.url'})} style={{ width:300, }}/> </Form.Item> <MinusCircleOutlined onClick={() => remove(name)} /> </Space> ))} <Form.Item > <Button style={{width: 405}} type="dashed" onClick={() => add()} block icon={<PlusOutlined />}> <FormattedMessage id='pages.record.info.content.add' /> </Button> </Form.Item> </> )} </Form.List> <Form.Item > <Space> <Button type="primary" htmlType="submit"> <FormattedMessage id='pages.save' /> </Button> </Space> </Form.Item> </Form> </Card> </div> </PageHeaderWrapper> ); }; export default RecordInformation;
// record.js文件 import { request } from 'umi'; import { formatReqUrl } from '../../common'; export async function saveRecordInfomation(data) { console.log(data) return request('/beian',{method:'POST', data: data}); } export async function getRecordInfomation() { return request('/beian',{method:'GET'}); }
前端向后端传送的是一个对象数组,也就是这种格式:[{label: ‘xxx’, value: ‘xxx’}]
后端用Go实现,因为每次新增的信息可能不一样,所以每次新增的时候,会先删除旧的数据,再插入。
代码如下:
// 定义结构体 type Beian struct { Label string `bson:"label" json:"label"` Value string `bson:"value" json:"value"` DefaultField `bson:",inline"` } // controller func (ctl *BeianController) Post(c *gin.Context) resp.JSON { c.Set("log-opt", "创建beian") doc := []models.Beian{} if err := c.ShouldBind(&doc); err != nil { return resp.Error(http.StatusBadRequest, gin.H{}, err) } c.Set("log-content", models.Doc2string(doc)) id, err := ctl.srv.Insert(doc) if err != nil { return resp.Error(http.StatusInternalServerError, gin.H{}, err) } return resp.Success(gin.H{"id": id}) } //service func (i *BeianServiceImpl) Insert(doc []models.Beian) (primitive.ObjectID, error) { ctx := context.Background() // 先删除 _, err := i.m.DB.Collection(BeianColl).RemoveAll(ctx, bson.M{}) if err != nil { return primitive.NilObjectID, err } // 再保存 var insertedID primitive.ObjectID for _, info := range doc { result, err := i.m.DB.Collection(BeianColl).InsertOne(ctx, &info) if err != nil { return primitive.NilObjectID, err } if insertedID.IsZero() { insertedID = result.InsertedID.(primitive.ObjectID) } } return insertedID, nil }
最终效果图如下:
到此这篇关于react实现动态增减表单项的文章就介绍到这了,更多相关react动态增减表单项内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!