首页 > 解决方案 > React:返回 ui 组件(如 toast)的服务?

问题描述

要求:在成功/错误/警告/信息的屏幕右下角显示 toast。

我可以创建一个 toast 组件并将其放置在我想要显示 toast 的任何组件上,但这需要我将 Toast 组件放在我打算显示 toast 的每个组件上。或者,我可以将它放在根组件上并以某种方式管理显示/隐藏(保持状态)。

我想知道的是有类似以下的东西

export class NotificationService {
    public notify = ({message, notificationType, timeout=5, autoClose=true, icon=''}: Notification) => {
        let show: boolean = true;
        let onClose = () => {//do something};
        if(autoClose) {
            //set timeout
        }
        return show ? <Toast {...{message, notificationType, onClose, icon}} /> : </>;
    }
}

并在我需要展示敬酒的地方调用此服务。这是实现所需功能的正确方法吗?

标签: reactjs

解决方案


您可以使用 AppContext 来管理 toast 的状态,并使用钩子随时触发它。

吐司上下文:

import React, { createContext, useContext, useState } from 'react';

export const ToastContext = createContext();

export const useToastState = () => {
  return useContext(ToastContext);
};

export default ({ children }) => {
  const [toastState, setToastState] = useState(false);
  const toastContext = { toastState, setToastState };
  return <ToastContext.Provider value={toastContext}>{children}</ToastContext.Provider>;
};

应用程序:

<ToastProvider>
   <App/>
   <Toast show={toastState}/>
</ToastProvider>

然后在您的应用程序中的任何地方,您都可以执行以下操作:

import {useToastState} from 'toastContext'
const {toastState, setToastState} = useToastState(); 
setToastState(!toastState);

推荐阅读