簡體   English   中英

NextJS 組件淡化已刪除的組件

[英]NextJS component takes fade of removed component

因此,我正在使用 NextJS 和 tailwind 為我的應用程序創建一個通知提供程序,但是當我顯示多個通知並且最上面的通知被刪除時,下面的通知將接管它的淡入淡出值,我該如何解決這個問題? 在此處輸入圖像描述

import { createContext, useState, useContext } from "react";

const Context = createContext();

const Provider = ({ children }) => {
    const [notifications, setNotifications] = useState([]);

    const exposed = {
        addNotification: (type, text, autoClose) => {
            const id = Math.random()
            setNotifications(notifications => [...notifications, { id, type, text, autoClose, fade: false }]);
            if (autoClose) {
                setTimeout(() => {
                    removeNotification(id);
                }, 5000);
            }
        },
    };

    const removeNotification = (id) => {
        setNotifications(notifications => notifications.map(n => n.id === id ? { ...n, fade: true } : n));
        setTimeout(() => {
            setNotifications(notifications => notifications.filter(n => n.id !== id));
        }, 1000);
    }

    return (
        <Context.Provider value={exposed}>
            {children}
            {notifications.length > 0 ? <div className="z-50 fixed top-5 right-5 text-right">
                {notifications.map((notification, index) => {
                    switch (notification.type) {
                        case 'info':
                            return <Info text={notification.text} key={index} remove={() => removeNotification(notification.id)} fade={notification.fade} />
                        /* other cases */
                    }
                })}
            </div> : null}
        </Context.Provider>
    );
}

function Info({ remove, text, fade }) {
    return (
        <div className={`flex items-center w-fit mt-2 mr-0 ml-auto transition-opacity ease-in duration-1000 ${!fade?'opacity-100':'opacity-0'}`}>
            {/* content */}
        </div>
    )
}

export const useProvider = () => useContext(Context);

export default Provider;

可能還有其他問題需要解決,但對於具有動態變化項目的列表,請考慮避免使用index作為唯一鍵,以防止列表變化時可能發生沖突。

也許嘗試在發布的示例中使用notification.id作為鍵:

<Context.Provider value={exposed}>
  {children}
  {notifications.length > 0 ? (
    <div className="z-50 fixed top-5 right-5 text-right">
      {notifications.map((notification, index) => {
        switch (notification.type) {
          case "info":
            return (
              <Info
                text={notification.text}
                // 👇 Use id as unique keys
                key={notification.id}
                remove={() => removeNotification(notification.id)}
                fade={notification.fade}
              />
            );
          /* other cases */
        }
      })}
    </div>
  ) : null}
</Context.Provider>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM