当前位置: 首页 > article >正文

React modal暴露ref简洁使用

  • 父组件使用
import { useRef } from 'react'
import { FormModal } from './modal'

const IndexRoute = () => {
  const formRef = useRef<any>()
  const openModal = (row?: any) => {
    const params = {
      title: row?.id ? `【${row.name}】编辑` : '创建',
      isView: false,
      row,
      api: row?.id ?  editXXX : createXXX,
      refreshList: () => proTableProps.actionRef.current?.reload()
    }
    formRef.current?.acceptParams(params)
  }

  return (
    <>
    <Button onClick={openModal}>open modal</Button>
      <FormModal ref={formRef} />
 		others page content
    </>
  )
}

export default IndexRoute

  • 子组件
import { Icons } from '@/components/antd-icons'
import { Button, Form, Input, message, Modal, Upload } from 'antd'
import { forwardRef, useEffect, useImperativeHandle, useState } from 'react'

export const FormModal = forwardRef((props: any, ref) => {
  const [form] = Form.useForm()
  const [confirmloading, setConfirmloading] = useState<boolean>(false)
  const [visible, setVisible] = useState(false)
  const [modalProps, setModalProps] = useState<any>({
    isView: false,
    title: '',
    row: {},
    api: () => {}
  })

  const { isView, title, row, api, refreshList } = modalProps

  const onCancel = () => {
    setConfirmloading(false)
    form.resetFields()
    setVisible(false)
  }

  const acceptParams = (params: any) => {
    setModalProps(params)
    setVisible(true)
    params.row ? form.setFieldsValue({ ...params.row }) : form.resetFields()
  }

  const onOk = async () => {
    form.validateFields().then(async formValue => {
      setConfirmloading(true)
      const res = await api({ ...formValue, id: row?.id })
      if (res) {
        message.success(`操作成功`)
        onCancel()
        refreshList()
      }
      setConfirmloading(false)
    })
  }

  useImperativeHandle(
    ref,
    () => ({
      acceptParams
    }),
    []
  )

  useEffect(() => {
    row && Object.keys(row)?.length > 0
      ? form.setFieldsValue({ ...row })
      : form.resetFields()
  }, [row])

  const normFile = (e: { fileList: any }) => {
    if (Array.isArray(e)) {
      return e
    }
    return e && e.fileList
  }

  return (
    <Modal
      forceRender
      title={title}
      open={visible}
      onOk={onOk}
      onCancel={onCancel}
      confirmLoading={confirmloading}
      destroyOnClose={true}
    >
      <Form
        form={form}
        disabled={isView}
        initialValues={row}
        layout="horizontal"
        labelCol={{ span: 4 }}
        size="small"
      >
        <Form.Item
          label="名称"
          name="name"
          rules={[{ required: true, message: '请输入版本名称!' }]}
        >
          <Input placeholder="name" />
        </Form.Item>
         {/* 文件上传form包裹demo */}
        <Form.Item
          name="calibration_zip"
          label="附件"
          valuePropName="fileList"
          getValueFromEvent={normFile}
        >
          <Upload maxCount={1} beforeUpload={() => false}>
            <Button size="small" icon={<Icons.UploadOutlined />}>
              上传
            </Button>
          </Upload>
        </Form.Item>
      </Form>
    </Modal>
  )
})

http://www.kler.cn/news/342252.html

相关文章:

  • 【uniapp小程序】使用cheerio去除字符串中的HTML标签并获取纯文本内容
  • 性能优化-SQL查询优化技巧全解
  • 服装生产管理的数字化转型:SpringBoot框架
  • Serilog文档翻译系列(八) - 记录器的生命周期、可靠性
  • Android -- [SelfView] 自定义多色渐变背景板
  • C/C++语言三大结构练习题(持续更新。。。)
  • 什么是矩阵系统,怎么选择矩阵系统,怎么oem贴牌,怎么源码搭建
  • Oracle RAC IPC Send timeout detected问题分析处理
  • 免费气象可视化的前端框架概述
  • 每日一面 day03
  • 论文翻译 | Fairness-guided Few-shot Prompting for LargeLanguage Models
  • 每天一个数据分析题(四百九十八)- Apriori算法
  • 毕业设计选题:基于php+vue+uniapp的新闻资讯小程序
  • CocosCreator基于jenkins自动构建
  • MQTT vs HTTP:谁更适合物联网?
  • [软件工程]—TFTP协议简要解析
  • wasm在云原生领域的运用
  • 【进阶OpenCV】 (6)--指纹识别
  • 每天一个数据分析题(四百九十九)- 数据集
  • 跨界的胜利:机器学习与神经网络的物理之光