首頁 > web前端 > js教程 > 我在反應打字稿中創建了一個自訂模態元件。

我在反應打字稿中創建了一個自訂模態元件。

DDD
發布: 2024-09-19 06:16:08
原創
1002 人瀏覽過

I create a custom Modal component in react   typescript.

我在 React TypeScript 中建立了一個自訂 Modal 元件。

模態.tsx

// src/components/ui/Modal.tsx
import React, { useState, useEffect, useRef } from 'react';

interface ModalProps {
  isOpen: boolean;
  onClose: () => void;
  children: React.ReactNode;
  dismissable?: boolean;
  closeOnEsc?: boolean;
  closeButtonLabel?: string;
  size?: 'small' | 'medium' | 'large';
  position?: 'center' | 'top' | 'bottom';
}

const Modal: React.FC<ModalProps> = ({
  isOpen,
  onClose,
  children,
  dismissable = true,
  closeOnEsc = true,
  closeButtonLabel = '×',
  size = 'medium',
  position = 'center',
}) => {
  const [isModalOpen, setIsModalOpen] = useState(isOpen);
  const modalRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    setIsModalOpen(isOpen);
  }, [isOpen]);

  useEffect(() => {
    const handleOutsideClick = (event: MouseEvent) => {
      if (dismissable && modalRef.current && !modalRef.current.contains(event.target as Node)) {
        onClose();
      }
    };

    const handleEscKey = (event: KeyboardEvent) => {
      if (closeOnEsc && event.key === 'Escape') {
        onClose();
      }
    };

    if (isModalOpen) {
      document.addEventListener('mousedown', handleOutsideClick);
      document.addEventListener('keydown', handleEscKey);
    }

    return () => {
      document.removeEventListener('mousedown', handleOutsideClick);
      document.removeEventListener('keydown', handleEscKey);
    };
  }, [isModalOpen, onClose, dismissable, closeOnEsc]);

  if (!isModalOpen) {
    return null;
  }

  const getSizeStyle = () => {
    switch (size) {
      case 'small':
        return { width: '300px', maxWidth: '100%' };
      case 'large':
        return { width: '800px', maxWidth: '100%' };
      default:
        return { width: '500px', maxWidth: '100%' };
    }
  };

  const getPositionStyle = () => {
    switch (position) {
      case 'top':
        return { alignItems: 'flex-start' };
      case 'bottom':
        return { alignItems: 'flex-end' };
      default:
        return { alignItems: 'center' };
    }
  };

  return (
    <div style={{
      position: 'fixed',
      top: 0,
      left: 0,
      right: 0,
      bottom: 0,
      backgroundColor: 'rgba(0, 0, 0, 0.5)',
      display: 'flex',
      justifyContent: 'center',
      zIndex: 1000,
      ...getPositionStyle(),
    }}>
      <div
        ref={modalRef}
        style={{
          backgroundColor: 'white',
          padding: '20px',
          borderRadius: '8px',
          maxHeight: '80vh',
          overflow: 'auto',
          position: 'relative',
          ...getSizeStyle(),
        }}
      >
          <button
            onClick={onClose}
            style={{
              position: 'absolute',
              top: '10px',
              right: '10px',
              background: 'none',
              border: 'none',
              fontSize: '18px',
              cursor: 'pointer',
            }}
          >
            {closeButtonLabel}
          </button>
        {children}
      </div>
    </div>
  );
};

export default Modal;
登入後複製

應用程式.tsx

import Modal from "@/components/ui/Modal";
import { useState } from "react";

export default function Home() {
  const [visible, setVisible] = useState(false);

  return (
    <main>
      <button onClick={() => setVisible(true)}>isOpen</button>
      <Modal position="bottom" isOpen={visible} onClose={() => setVisible(false)}>
        <h2>Modal Content</h2>
        <p>This is a simple modal component.</p>
      </Modal>
    </main>
  );
}
登入後複製

以上是我在反應打字稿中創建了一個自訂模態元件。的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:dev.to
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板