reactjs - 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}} /> : </>;
}
}
并在我需要展示敬酒的地方调用此服务。这是实现所需功能的正确方法吗?
解决方案
您可以使用 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);
推荐阅读
- netbeans - EntityManagerFactory 中的 java.lang.NullPointerException
- sql-server - 访问其他表列数据给出空结果
- node.js - 文件上传后,使用节点 js 和 sequelize 更新方法在实时服务器中未更新响应路径
- c# - 使用cefsharp在c#和JS之间发送和接收变量
- angular - 一旦我将组件留在 Angular 中,就停止调用连续函数
- php - 如何删除单行txt文件的行尾符号(使用sed/awk)?
- authentication - 在 ASP.NET Core 中进行社交登录后,禁止用户并将用户重定向到不同的页面
- javascript - 使用 pug 构建 express.js 应用程序时出错
- ios - 如何触发ipa安装完成事件?
- rust - 如何简化重复功能逻辑