[React] Custom package ant-design pop-up window

Article directory

  • Pop-up package file:ImportModal.tsx
import React, {
    
     useState, useImperativeHandle, forwardRef } from 'react'
import {
    
     Form, Modal, Select } from 'antd'
type TParams = {
    
     ttl: any[] }
// forwardRef : 传递ref
export 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.current
    useImperativeHandle(
      ref,
      () => ({
    
    
        show:(params: TParams) => {
    
    
            // 保存参数
            setParams(params)
            /** 改变状态 */
            setIsModalVisible(true)  
          },
      }),
      []
    )

    return (
      <Modal
        title='弹窗'
        visible={
    
    isModalVisible}
        onOk={
    
    handleOk} 
        onCancel={
    
    handleCancel}
      >
        <div>弹窗内容</div>
      </Modal>
    )
  }
)
  • Use a custom popup
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

Guess you like

Origin blog.csdn.net/qq_45677671/article/details/131371250