You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于React Hook实现可复用通知组件及调用方法

React 通知封装方法的调用实现流程

核心逻辑说明

你已经完成了通知逻辑的公共封装,调用时不需要重复处理通知的公共配置,只需要在对应事件中传入业务相关的参数即可完成不同类型通知的触发。

完整实现步骤

1. 修正导入冗余问题

  • 保留App组件中必须挂载的 <ReactNotification /> 全局渲染容器
  • 删除App中重复从 react-notifications-component 导入的 store 实例(因为这个已经在notif.js的封装逻辑内部完成引用了)
  • 修正 notify 方法的导入路径,确保能正确指向同目录下的 notif.js 文件,避免模块解析报错

2. 实现三个按钮的事件处理函数

直接在组件内部定义三个对应点击事件的方法,调用已封装的notify方法,分别传入success、danger、warning三种类型的配置即可。

3. 可直接运行的完整App组件代码

import React from 'react'
import ReactNotification from 'react-notifications-component'
import 'react-notifications-component/dist/theme.css'
// 修正导入路径,补充./标识代表当前目录下的文件
import { notify } from './notif'

function App() {
    // 触发成功类型通知
    const openNotify1 = () => {
        notify({
            type: "success",
            title: "操作成功",
            message: "请求已顺利执行"
        })
    }

    // 触发错误类型通知
    const openNotify2 = () => {
        notify({
            type: "danger",
            title: "操作失败",
            message: "请求执行出错,请稍后重试"
        })
    }

    // 触发警告类型通知
    const openNotify3 = () => {
        notify({
            type: "warning",
            title: "操作提示",
            message: "当前操作存在风险,请确认后执行"
        })
    }

    return (
        <div className="App">
            {/* 通知全局渲染容器,必须挂载才能正常显示通知 */}
            <ReactNotification />
            <button onClick={openNotify1}>get Notify Success</button>
            <button onClick={openNotify2}>get Notify Danger</button>
            <button onClick={openNotify3}>get Notify Warning</button>
        </div>
    );
}
export default App;

注意事项

  • 你在封装的notify方法中配置了animate__fadeIn、animate__fadeOut的动画类,需要在项目入口文件中引入animate.css的样式,否则弹出/消失动画不会正常生效
  • 通知的默认自动关闭时长、弹出位置、插入方向等公共配置已经在notif.js中统一设置,所有调用notify方法的场景都会复用这套配置,后续需要调整全局效果时只需要修改notif.js中的公共配置即可,不需要逐个修改业务代码

内容的提问来源于stack exchange,提问作者miladjurablu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.23 06:24:05