文章目录
弹窗封装文件 :ImportModal.tsx
import React, {useState, useImperativeHandle, forwardRef } from 'react'import {Form, Modal, Select } from 'antd'type TParams = {ttl: any[] }// forwardRef : 传递refexport const ImportTTLModal = forwardRef<any>((props, ref) => {const [params, setParams] = useState<any>()const [isModalVisible, setIsModalVisible] = useState(false);// 确定事件const handleOk = () => {setIsModalVisible(false);};// 取消事件const handleCancel = () => {setIsModalVisible(false);};// useImperativeHandle:自定义 ref.currentuseImperativeHandle(ref,() => ({show:(params: TParams) => {// 保存参数setParams(params)/** 改变状态 */setIsModalVisible(true) },}),[])return (<Modaltitle='弹窗'visible={isModalVisible}onOk={handleOk} onCancel={handleCancel}><div>弹窗内容</div></Modal>)})
使用自定义弹窗
import {Button, } from 'antd'import React, {useRef, useState } from 'react'import {ImportModal } from './components/ImportModal'const Main: React.FC<any> = () => {const refImportModal = useRef<any>(null)const ttl = [7, 14, 30, 60, 90, 120, 150, 180, 270, 360, 720, -1]const showModal = () => {// 显示弹窗并传参。refImportModal.current?.show({ttl: ttl,})}return (<div><Button onClick= {showModal } >弹出弹窗< /Button>< ImportModal ref = {refImportModal } /></div>)}export default Main