当前位置: 代码网 > it编程>编程语言>Javascript > react实现动态增减表单项的示例代码

react实现动态增减表单项的示例代码

2024年06月11日 Javascript 我要评论
在做项目的时候,甲方给的信息有限,网页的备案信息写成固定的,如下图所示:之后验收的时候,甲方要求把这个备案信息写成动态的,可以自增减,就去react组件库看看有没有具体的实现,果真有,具体实现如下:i

在做项目的时候,甲方给的信息有限,网页的备案信息写成固定的,如下图所示:

之后验收的时候,甲方要求把这个备案信息写成动态的,可以自增减,就去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动态增减表单项内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com