当前位置: 首页 > 工具软件 > Form'n'Field > 使用案例 >

react form.list设置默认值

解浩渺
2023-12-01

项目场景:

创建投票用到antd里的form.list 动态增删表单项

问题描述:

我在form.list 的一个formItem里有一个图片上传组件,我想上传完图片后把图片地址绑定到这个formItem上,之前我就用了

form.setFieldsValue({votingOptions:[subjectUrl:item?.response?.realUrl]})

但是这么写完之后虽然图片的值是绑定上了,但是这个form.list里还有另外两个输入框,这两个控件的值会被重置


原因分析:

因为设置值的时候我只是设置了这个数组里的一个值,其他两个没有管,所以会被重置。


解决方案:

let votingOptions = (form.getFieldsValue()).votingOptions
votingOptions[field.name] = {
	...votingOptions[field.name],
	subjectUrl: item?.response?.realUrl
	}
form.setFieldsValue({ votingOptions });
  • 这样写的话就会先拿到之前的值,再设置你想要设置的值就不会有问题了,也就不会重置其他值了。
  • 源码送上
import React, { useState, useEffect } from 'react';
import { shallowEqual, useDispatch, useSelector } from 'react-redux';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { Card, Spin, Form, Input, Row, Col, Select, DatePicker, Button, Space } from 'antd';
import { DeleteOutlined, PlusOutlined } from '@ant-design/icons';
import ImgUploader from '@/components/common/ImgUploader';
// import router from 'umi/router'
import { routerRedux } from 'dva/router';

import moment from 'moment'
import Styles from 'Styles.css'

const { Option } = Select;
const { RangePicker } = DatePicker;

const VotingDetail: React.FC = (props) => {

  console.log(props)
  console.log(props.location.query)
  // this.props.releaseOrgList
  const initData = props.location.query
  console.log(initData)
  const [form] = Form.useForm();
  const dispatch = useDispatch();
  const { releaseOrgList } = useSelector(
    state => ({
      releaseOrgList: state.global.releaseOrgList,
    }),
    shallowEqual,
  );

  useEffect(() => {
    // dispatch({
    //   type: 'votingActivity/fetchTableList',
    //   payload: {},
    // });
    form.resetFields()
  }, []);

  const submit = () => {
    console.log(form.getFieldsValue())
    form.validateFields().then((formValue) => {
      console.log(formValue)
      formValue['appKey'] = JSON.parse(localStorage.getItem("userInfo")).userInfo.appKey
      formValue['allowTime'] = '1'
      formValue['examType'] = '3'
      formValue.startTime = moment(formValue.startTime).format('YYYY-MM-DD HH:mm:ss')
      formValue.endTime = moment(formValue.endTime).format('YYYY-MM-DD HH:mm:ss')
      formValue.votingOptions.forEach((item: any, index: any) => {
        item.orderNum = index
        if(item.subjectUrl == undefined){
          item.subjectUrl = 'https://saas2.ltzhdj.com/saasuaa/images/logo.png'
        }
      })
      formValue['subjectList'] = JSON.stringify(formValue.votingOptions)
      formValue.insertOrganize.forEach((item: any, index: any) => {
        formValue[`insertOrganize[${index}].organizeId`] = item
      })
      if (formValue.releaseType == '0') {
        formValue['isPublic'] = 'Y'
      } else if (formValue.releaseType == '1') {
        formValue['isPublic'] = 'N'
      }
      delete formValue.insertOrganize
      // formValue['examPaperSaasVo'] = JSON.stringify({subjectList:formValue.votingOptions})
      delete formValue.votingOptions
      console.log(formValue)
      dispatch({
        type: 'votingActivity/insertVoting',
        payload: formValue,
        success: (res) => {
          if (res.success) {
            setTimeout(() => {
              props.history.goBack()
            }, 1000)
          }
        }
      })
    })

  };

  const imgProps = {
    maxSize: 5,
    maxLength: -1,
    fileType: 'image',
    accept: 'image/*',
    fileDir: 'education/resourceBank',
    buttonText: '上传图片',
  };
<PageHeaderWrapper>
      <Spin spinning={false} tip="加载中...">

        <Form form={form} layout="vertical"
          initialValues={
            initData.name ? {
            ...initData,
            startTime: moment(new Date(initData.startTime), 'YYYY-MM-DD'),
            endTime: moment(new Date(initData.endTime), 'YYYY-MM-DD')
          } : undefined}
          // initialValues={initArray}
        >

          <Card className="" title="基本信息">
            <Row gutter={24}>
              <Col span={8}>
                <Form.Item name="examName" label="活动名称"
                  rules={[{ required: true, message: '请输入活动名称' }]}
                >
                  <Input placeholder="请输入活动名称" />
                </Form.Item>
              </Col>

              <Col span={8}>
                <Form.Item name="organizeId" label="发布组织"
                  rules={[{ required: true, message: '请选择发布组织' }]}
                >
                  <Select placeholder="请选择发布组织" >
                    {releaseOrgList?.map((item, index) => {
                      return <Option value={item.value}>{item.title}</Option>
                    })}
                    {/* <Option value="1">组织一</Option>
                    <Option value="2">组织二</Option> */}
                  </Select>
                </Form.Item>
              </Col>

              <Col span={8}>
                <Form.Item name="insertOrganize" label="可见范围"
                  rules={[{ required: true, message: '请选择可见范围' }]}
                >
                  <Select placeholder="请选择可见范围" mode="multiple">
                    {releaseOrgList?.map((item, index) => {
                      return <Option value={item.value}>{item.title}</Option>
                    })}
                    {/* <Option value="1">组织一</Option> */}
                    {/* <Option value="2">组织二</Option> */}
                  </Select>
                </Form.Item>
              </Col>

            </Row>
            <Row gutter={24}>

              <Col span={8}>
                <Form.Item name="startTime" label="开始时间"
                  rules={[{ required: true, message: '请选择开始时间' }]}
                >
                  <DatePicker style={{ width: '100%' }} placeholder="请选择日期" />
                </Form.Item>
              </Col>

              <Col span={8}>
                <Form.Item name="endTime" label="结束时间"
                  rules={[{ required: true, message: '请选择结束时间' }]}
                >
                  <DatePicker style={{ width: '100%' }} placeholder="请选择日期" />
                </Form.Item>
              </Col>
              <Col span={8}>
                <Form.Item name="releaseType" label="是否公开"
                  rules={[{ required: true, message: '请选择' }]}
                >
                  <Select placeholder="请选择" >
                    <Option value="0">公开</Option>
                    <Option value="1">不公开</Option>
                  </Select>
                </Form.Item>
              </Col>
            </Row>
            <Row gutter={24}>

              <Col span={24}>
                <Form.Item name="activityContent" label="活动简介"
                  rules={[{ required: true, message: '请填写活动简介' }]}
                >
                  <Input.TextArea
                    autoSize={{ minRows: 4, maxRows: 6 }}
                    placeholder="请输入活动简介"
                  />
                </Form.Item>
              </Col>

            </Row>
          </Card>

          <Card title="投票选项" style={{
            marginTop: '20px'
          }}>
            <Form.List name="votingOptions"
              rules={[
                {
                  validator: async (_, votingOptions) => {
                    console.log(votingOptions);
                    if (votingOptions == undefined || votingOptions.length < 0) {
                      return Promise.reject(new Error('至少填写一项'));
                    }
                  },
                },
              ]}
            >
              {(fields, { add, remove }, { errors }) => {
                return (
                  <div style={{ paddingBottom: '20px' }}>
                    {fields.map(field => (
                      <Card>
                        <Row>
                          <Col span={1}>
                            {field.name + 1}
                          </Col>
                          <Col span={20}>
                            <Form.Item
                              {...field}
                              name={[field.name, 'subjecetName']}
                              fieldKey={[field.fieldKey, 'subjecetName']}
                              rules={[{ required: true, message: '请输入选项标题' }]}
                            >
                              <Input placeholder="请输入投票标题(必填)" />
                            </Form.Item>
                          </Col>
                          <Col span={2}>
                            <DeleteOutlined
                              style={{ marginLeft: '16px' }}
                              onClick={() => {
                                remove(field.name);
                              }}
                            />
                          </Col>
                        </Row>
                        <Row>
                          <Col span={1}>{null}</Col>
                          <Col span={20}>
                            <Form.Item
                              {...field}
                              name={[field.name, 'analysis']}
                              fieldKey={[field.fieldKey, 'analysis']}
                              rules={[{ required: true, message: '请输入投票详情' }]}
                            >
                              <Input
                                style={{ height: '104px', width: 'calc(100% - 120px' }}
                                placeholder="请输入投票详情(必填)"
                              />
                            </Form.Item>
                          </Col>
                          <Col span={2}>
                            <div style={{ position: 'absolute', left: '-104px' }}>
                              <Form.Item
                                {...field}
                                name={[field.name, 'subjectUrl']}
                                fieldKey={[field.fieldKey, 'subjectUrl']}
                              // rules={[{ required: true, message: 'Missing last name' }]}
                              >
                                <ImgUploader
                                  {...imgProps}
                                  getFileList={(value: any) => {
                                    console.log(value);
                                    // let images: any = [];
                                    if (value.length > 0) {
                                      value.map((item: any) => {
                                        if (item.response || item.url) {
                                          let votingOptions = (form.getFieldsValue()).votingOptions
                                          votingOptions[field.name] = {
                                            ...votingOptions[field.name],
                                            subjectUrl: item?.response?.realUrl
                                          }
                                          form.setFieldsValue({ votingOptions });
                                        }
                                        return item;
                                      });

                                    }
                                  }}
                                  defaultFileList={[]}
                                />
                              </Form.Item>
                            </div>
                          </Col>
                        </Row>
                      </Card>
                    ))}

                    <Form.Item>
                      <Button
                        type="dashed"
                        onClick={() => { add(); }}
                        block
                      >
                        <PlusOutlined /> 新增一条
                      </Button>
                      <Form.ErrorList errors={errors} />
                    </Form.Item>
                  </div>
                );
              }}
            </Form.List>
          </Card>
        </Form>
        <Card
          style={{
            position: 'fixed',
            bottom: '0',
            left: '0',
            width: '100%',
            display: 'flex',
            justifyContent: 'flex-end',
          }}
        >
          <Button style={{ marginRight: '16px' }} onClick={() => {
            // router.goBack()
            window.history.go(-1);
          }}>返回</Button>
          <Button type="primary" onClick={submit}>
            确定
          </Button>
        </Card>
      </Spin>
    </PageHeaderWrapper>
 类似资料: