react弹框把组件ui和调用方法结合起来

147 阅读1分钟

react的组件具备非常好的灵活性,ui是写JSX的形式嵌入任何JS中

import { Modal, ModalProps } from '@nbit/arco'
import { renderRoot } from '@/helper/render'
import { ReactNode } from 'react'
import { t } from '@lingui/macro'
import Styles from './index.module.css'

export type PopBoxProps = {
  visible: boolean
  title?: string
  content: ReactNode
  onClose: () => void
  onCommit: () => void
} & Pick<ModalProps, 'cancelText' | 'okText'>

function PopBox({
  visible,
  title = t`helper_message_fugvl05ct4`,
  content,
  onClose,
  onCommit,
  okText = t`components_pop_box_index_xjmp7i51ci`,
  cancelText = t`features_group_components_comfirm_btn_pop_index_2sr1guu0iy`,
  ...rest
}: PopBoxProps) {
  const handleCancel = () => {
    return onClose?.()
  }

  const handleOk = () => {
    return onCommit?.()
  }

  return (
    <Modal
      className={Styles.popbox}
      closable={false}
      title={<div style={{ textAlign: 'left' }}>{title}</div>}
      visible={visible}
      onCancel={handleCancel}
      onOk={handleOk}
      okText={okText}
      cancelText={cancelText}
      {...rest}
    >
      <p>{content}</p>
    </Modal>
  )
}

export async function popBoxConfirm(title: string, content: ReactNode, config: ModalProps = {}) {
  return new Promise((resolve, reject) => {
    renderRoot(unmount => {
      const onConfirm = () => {
        unmount()
        resolve({})
      }
      const onClose = () => {
        unmount()
        reject()
      }
      return <PopBox onClose={onClose} {...config} onCommit={onConfirm} visible title={title} content={content} />
    })
  })
}

export async function popBoxConfirmWithLoading({
  onCommit: propsConCommit,
  ...props
}: Omit<PopBoxProps, 'onClose' | 'visible'>) {
  return new Promise((resolve, reject) => {
    renderRoot(unmount => {
      const onConfirm = async () => {
        await propsConCommit?.()
        unmount()
        resolve({})
      }
      const onClose = () => {
        reject()
        unmount()
      }
      return <PopBox onClose={onClose} {...props} onCommit={onConfirm} visible />
    })
  })
}

export default PopBox