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

如何在Next.js按钮中集成Toast通知组件并移除示例按钮?

解决Next.js中React Toast组件集成问题(移除示例按钮并触发通知)

我明白你的困扰——你想把那个带示例按钮的Toast组件改成只负责显示通知,并且在proses函数执行完成后根据结果触发它。咱们一步步来修改代码:

第一步:重构Notifications组件(移除示例按钮,暴露通知触发方法)

首先修改你的Notifications.js,删掉自带的示例按钮,同时把触发通知的方法暴露出来,让父组件可以调用。另外咱们把通知的配置改成可传入的参数,这样你能根据成功/失败显示不同内容:

import React, { Component } from 'react';
import NotificationAlert from 'react-notification-alert';

class Notifications extends Component {
  // 定义触发通知的方法,支持传入自定义配置
  showNotification = (options) => {
    // 配置默认参数,避免每次都重复写
    const defaultOptions = {
      place: 'tc',
      type: "success",
      icon: "now-ui-icons ui-1_bell-53",
      autoDismiss: 1.25
    };
    // 合并默认配置和传入的自定义配置
    const finalOptions = { ...defaultOptions, ...options };
    this.refs.notify.notificationAlert(finalOptions);
  }

  render() {
    return (
      <div>
        {/* 只保留核心的NotificationAlert实例,移除示例按钮 */}
        <NotificationAlert ref="notify" zIndex={9999} />
      </div>
    );
  }
}

export default Notifications;

第二步:在Home组件中集成并触发Toast通知

接下来修改你的index.js,这里有两个关键问题需要修正:

  • 你直接在onClick里渲染<Notifications />是无效的,React组件只能在render函数中渲染
  • 需要通过useRef获取Notifications组件的实例,才能调用它的触发方法
  • 另外Profile是React组件,不能像普通函数那样直接调用let data = Profile();,要通过JSX渲染

修改后的index.js(附带数据获取逻辑优化):

import { proses } from '../public/static/query.js';
import Notifications from './Notifications';
import useSWR from 'swr';
import { useRef } from 'react'; // 引入useRef用于获取组件实例

const fetcher = (...args) => fetch(...args).then(res => res.json());

export default function Home() {
  const notificationRef = useRef(null); // 创建ref绑定Notifications组件
  // 把数据获取逻辑放到Home组件,方便直接使用data
  const { data, error } = useSWR('your-api-link-here', fetcher);

  if (error) return <div>failed to load</div>;
  if (!data) return <div>loading...</div>;

  return (
    <div>
      {/* 渲染获取到的数据 */}
      <div>{JSON.stringify(data)}</div>
      {/* 渲染Notifications组件并绑定ref */}
      <Notifications ref={notificationRef} />
      <button 
        className={styles2.btnNormal} 
        onClick={() => {
          const result = proses(data);
          if (result === "Copied to Clipboard!") {
            // 调用Toast组件的方法显示成功通知
            notificationRef.current.showNotification({
              message: <div>Copied to Clipboard!</div>,
              type: "success"
            });
            console.log("copied to clipboard!");
          } else {
            // 显示失败通知
            notificationRef.current.showNotification({
              message: <div>Item not found!</div>,
              type: "danger"
            });
            console.log("not found");
          }
        }}
      >
        Process
      </button>
    </div>
  );
}

这样修改后,你点击Process按钮时,就会根据proses函数的结果显示对应的Toast通知,而且Notifications组件里再也没有多余的示例按钮了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 16:42:37