react的antd checkbox组件,在编辑的时候无法初始化选中,我想了4个小时解决不了,原因是什么?

import React, { useState, useEffect, useRef } from 'react'
import {
  Form,
  Input,
  Select,
  Tooltip,
  Row,
  Col,
  message,
  Button,
  Typography,
  Card,
  Space,
  Modal,
  Popconfirm,
  Drawer,
  Checkbox,
  Tag,
  Spin,
} from 'antd'
import type { CheckboxValueType } from 'antd/es/checkbox/Group'
import { PlusCircleOutlined, FormOutlined, DeleteOutlined } from '@ant-design/icons'
import { getDemandProtocolTemplateGetItemList } from '@apps/apis'
import { formatTimeString } from '@/utils'
import moment from 'moment'

import { validatorByte } from '../../validator'

import style from './index.less'

const { TextArea } = Input
const layout: any = {
  colon: false,
  labelCol: { style: { width: '100px' } },
  wrapperCol: { span: 9 },
  labelAlign: 'left',
}

interface Iprops {
  currentRef: any
  fetchdata: any
  onBadge: (num: number, idx: number) => void
}

const TempletInfo: React.FC<Iprops> = (props: any) => {
  const { currentRef, fetchdata, onBadge } = props
  const [form] = Form.useForm()
  const [loading, setLoading] = useState<boolean>(false)
  const [isModalOpen, setIsModalOpen] = useState(false)
  const [isDrawerOpen, setIsDrawerOpen] = useState(false)
  const result = useRef<any>([])
  const [resultExport, setresultExport] = useState<any>([])
  const [idxInit, setidxInit] = useState(-1)
  const [idxInitSource, setidxInitSource] = useState(-1)
  const [itemSource, setitemSource] = useState<any>([])
  const [defaultCheckboxValue, setdefaultCheckboxValue] = useState<any>([])

  const DrawerOpen = (e, idx: number) => {
        setidxInitSource(idx)
                const defaultCheckboxValue = result.current[idx].protocolTemplateGroupItemList?.map(
                      (ele) => ele.id + '___' + ele.name,
                )
                let arr = [...defaultCheckboxValue]
                console.log(arr)
                setdefaultCheckboxValue(arr)
        setIsDrawerOpen(true)
  }

  const showModal = (e, idx: number) => {
    setidxInit(idx)
    if (idx > -1) {
      form.setFieldsValue({
        name: result.current[idx].name,
        sort: result.current[idx].sort,
      })
    }
    setIsModalOpen(true)
  }

  const handleOk = () => {
    form.validateFields().then((res) => {
      if (idxInit > -1) {
        result.current[idxInit]['name'] = res.name
        result.current[idxInit]['sort'] = res.sort || 0
      } else {
        result.current.push({
          name: res.name,
          sort: res.sort || 0,
          protocolTemplateGroupItemList: [],
        })
      }
      setresultExport(result.current)
      setIsModalOpen(false)
    })
  }

  const handleDelete = (idx) => {
    const arr = [...result.current]
    arr.splice(idx, 1)
    result.current = arr
    setresultExport(arr)
  }

  const handleCancel = () => {
    setIsModalOpen(false)
  }

  const onDrawerClose = () => {
    setIsDrawerOpen(false)
  }

  const onChangeCheckbox = (checkedValues: CheckboxValueType[]) => {
    const arr = [...result.current]
    const checkedValuesTMP = [...checkedValues]
    const checkedValuesArr = checkedValuesTMP.map((ele) => {
      let tmp = ele.split('___')
      return {
        id: tmp[0],
        name: tmp[1],
        sort: 0,
      }
    })
    arr[idxInitSource].protocolTemplateGroupItemList = []
    arr[idxInitSource].protocolTemplateGroupItemList = checkedValuesArr

    const defaultCheckboxValue = checkedValuesArr?.map((ele) => ele.id + '___' + ele.name)
    let arrtmp = [...defaultCheckboxValue]
    setdefaultCheckboxValue(arrtmp)

    result.current = arr
    setresultExport(arr)
  }

  useEffect(() => {
        setLoading(true)
        getDemandProtocolTemplateGetItemList().then((res) => {
          if (res.code === 1000) {
            setLoading(false)
            setitemSource(res.data)
          }
        })

    currentRef.current = {
      get: () =>
        new Promise((resolve: any) => {
          resolve({
            state: true,
            name: 'templet',
            data: result.current,
          }).catch((error) => {
            if (error && error.errorFields) {
            }
          })
        }),
    }
  }, [])

  useEffect(() => {
    if (fetchdata['protocolTemplateGroupList']?.length > 0) {
      result.current = fetchdata['protocolTemplateGroupList']
      setresultExport(result.current)

            setLoading(true)
            getDemandProtocolTemplateGetItemList().then((res) => {
              if (res.code === 1000) {
                setLoading(false)
                setitemSource(res.data)
              }
            })
    }
  }, [fetchdata['protocolTemplateGroupList']])

  return (
    <>
      <Spin spinning={loading}>
        <Drawer forceRender title="添加项目" placement="right" onClose={onDrawerClose} open={isDrawerOpen}>
          <Checkbox.Group
            style={{ width: '100%' }}
            key={defaultCheckboxValue}
            defaultValue={defaultCheckboxValue}
            onChange={(checkedValues) => onChangeCheckbox(checkedValues)}
          >
            {itemSource?.map((item, idx) => {
              return (
                <React.Fragment key={+new Date() + '_' + idx}>
                  <Row>
                    <Col span={24}>
                      <div style={{ fontWeight: 'bold', marginBottom: '10px' }}>{item.groupName}</div>
                    </Col>
                  </Row>
                  <Row>
                    {item.protocolItemGroupList?.map((item2, idx2) => {
                      return (
                        <React.Fragment key={+new Date() + '_' + idx + '_' + idx2}>
                          <Col span={6} style={{ display: 'inline-block' }}>
                            <div style={{ marginBottom: '15px' }}>
                              <Checkbox value={item2.id + '___' + item2.itemName}>{item2.itemName}</Checkbox>
                            </div>
                          </Col>
                        </React.Fragment>
                      )
                    })}
                  </Row>
                </React.Fragment>
              )
            })}
          </Checkbox.Group>
        </Drawer>
        <Modal title="新建分组" open={isModalOpen} onOk={handleOk} onCancel={handleCancel}>
          <Form {...layout} form={form} className={style.form}>
            <Form.Item
              label="分组名称"
              name="name"
              rules={[
                { required: true, message: '请输入分组名称' },
                {
                  validator: (r, v) => validatorByte(v, 60),
                },
              ]}
            >
              <Input maxLength={60} placeholder="请输入" />
            </Form.Item>
            <Form.Item label="排序" name="sort">
              <Input maxLength={60} placeholder="请输入" />
            </Form.Item>
          </Form>
        </Modal>
        <Space direction="vertical" size="middle" style={{ display: 'flex' }}>
          <Button type="primary" onClick={(e) => showModal(e, -1)}>
            新建分组
          </Button>
          {resultExport?.map((item, idx) => {
            return (
              <Card
                key={idx}
                title={item.name}
                bordered={true}
                style={{ background: '#f0f2f5' }}
                actions={[
                  <Button type="link" onClick={(e) => showModal(e, idx)}>
                    <FormOutlined />
                    编辑
                  </Button>,
                  <>
                    <Popconfirm
                      title={'确定删除吗'}
                      okText={'确定'}
                      cancelText={'取消'}
                      onConfirm={() => handleDelete(idx)}
                    >
                      <Button type="link" danger>
                        <DeleteOutlined />
                        删除
                      </Button>
                    </Popconfirm>
                  </>,
                ]}
              >
                {item.protocolTemplateGroupItemList?.map((item2, idx2) => {
                  return (
                    <Tag key={idx2} color="#1db599" style={{ marginRight: '10px' }}>
                      {item2.name}
                    </Tag>
                  )
                })}
                <br />
                <Button type="link" onClick={(e) => DrawerOpen(e, idx)}>
                  <PlusCircleOutlined />
                  添加项目
                </Button>
              </Card>
            )
          })}
        </Space>
      </Spin>
    </>
  )
}
export default TempletInfo

自己研究了4个多小时了,搞不定,react的ant design组件,编辑的时候,checkbox无法初始化选中

阅读 381
1 个回答

image.png

Checkbox Group 里用value控制下

推荐问题
logo
Microsoft
子站问答
访问
宣传栏