如何创建可重复使用的脉轮UI吐司

发布于 2025-02-13 09:05:16 字数 1258 浏览 2 评论 0原文

我正在将Chakra UI与我的下一个JS应用一起使用。 在某些情况下,我想使用 chakra ui toast 行动。
(对于单击登录时,我将发送请求到后端,并将显示成功或错误吐司,具体取决于结果) 而且,由于只能在单击之后调用吐司而不是编程,所以我创建了一个函数来执行此操作

import { useToast } from '@chakra-ui/react';
...

export default function SignInPage() {
    const toast = useToast();

    const resultToast = (status, title) => {
    return toast({
      position: "top",
      title: title,
      status: status,
      duration: 3000,
      isClosable: true,
    });

    const handleSubmit = (e) => {
        // talking to backend / database        

        if(success) {
            resultToast("success", "sign in successful");
        }
        else {
            resultToast("error", "sign in failed");
        }      
    }

    // sign in form
  };
}

,这完全可以正常工作,但是我想在多个页面上使用它,并且想要使其重复使用,但问题是:

  • 我不能将其作为JSX组件,因为它仅返回吐司元素,并且仅在单击时被调用。
  • 而且我不能在单独的文件中使其成为正常的函数,因为它使用了无法在函数中使用的Chakra UI的USEtoast Hook(或者也许我错了)。
  • 而且也无法从一个文件中导出结果数据函数,它显示“修饰符不能在此处出现”

当我使用Chakra UI时,因此不想安装任何其他吐司库。因此,有什么方法可以使此重复使用,否则我必须使用任何外部库或在所有页面上复制粘贴函数:D

I'm using chakra ui with my next js app.
On some event, I want to show a notification using chakra ui toast, after performing some action.

(For ex. on clicking sign in, I'll send request to backend, and will show success or error toast depending on the result)
And as this toast can only be invoked after click and not programatically, I've created a function to do so

import { useToast } from '@chakra-ui/react';
...

export default function SignInPage() {
    const toast = useToast();

    const resultToast = (status, title) => {
    return toast({
      position: "top",
      title: title,
      status: status,
      duration: 3000,
      isClosable: true,
    });

    const handleSubmit = (e) => {
        // talking to backend / database        

        if(success) {
            resultToast("success", "sign in successful");
        }
        else {
            resultToast("error", "sign in failed");
        }      
    }

    // sign in form
  };
}

This is working totally fine, but the thing is I want to use this on multiple pages, and want to make it reusable, but the issue is:

  • I can't make it a jsx component, as it returns only toast element and gets invoked only on click.
  • And I can't make it a normal function in separate file, as it uses useToast hook from chakra ui which can't be used in a function (Or maybe I'm wrong).
  • And also not able to export the resultToast function from one file, it shows "Modifiers can't appear here"

As I'm using chakra ui, so didn't want to install any other toast library. So is there any way to make this reusable or I'll have to use any external library or copy paste the function on all pages :D

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

Saygoodbye 2025-02-20 09:05:17

您可以使用 react-universal-flash 库库以浏览sextjs页面。

只需将flasher添加到_app.js

import { ChakraProvider} from "@chakra-ui/react";
import { Flasher } from "react-universal-flash";
import Message from "./Message";

function MyApp({ Component, pageProps }) {
  return (
    <ChakraProvider>
      <Flasher>
        <Message />
      </Flasher>
      <Component {...pageProps} />
    </ChakraProvider>
  );
}

codesandbox的脉轮 - ui以及react-universal-flash下方

react-universal-flash + chakra-ui

You can use react-universal-flash library to flash notification across nextjs pages .

Just add Flasher to _app.js

import { ChakraProvider} from "@chakra-ui/react";
import { Flasher } from "react-universal-flash";
import Message from "./Message";

function MyApp({ Component, pageProps }) {
  return (
    <ChakraProvider>
      <Flasher>
        <Message />
      </Flasher>
      <Component {...pageProps} />
    </ChakraProvider>
  );
}

Codesandbox sample of chakra-ui along with react-universal-flash is below

react-universal-flash + chakra-ui

挖鼻大婶 2025-02-20 09:05:16

我不知道您是否弄清楚了这一点,但是今天我遇到了同样的问题,这就是我用脉轮 - UI解决的。创建一个单独的函数并像这样写逻辑...

import { useToast } from "@chakra-ui/react";

export const CustomToast = () => {
    const toast = useToast();
    // types are: "success", "info", "warning", "error"

    const addToast = (newRes) => {
        toast({
            description:newRes.message, 
            status: newRes.type, 
            position:"top-right", 
            isClosable: true, 
            duration: 5000,
            variant: 'left-accent' 
        })
    }
    
    return { addToast };
}

然后从“ ../ path/to/file”中导入addtoast方法import {addToast} = CustomToast();并通过将破坏的对象传递到addtoast函数addToast({消息:“ insucy”,type:“ success”}) ... i来使用它。希望这对这里的其他人有帮助。

I don't know if you ever figured this out, but I ran into the same problem today, and here's how I resolved it with Chakra-UI. Create a separate function and write the logic like this...

import { useToast } from "@chakra-ui/react";

export const CustomToast = () => {
    const toast = useToast();
    // types are: "success", "info", "warning", "error"

    const addToast = (newRes) => {
        toast({
            description:newRes.message, 
            status: newRes.type, 
            position:"top-right", 
            isClosable: true, 
            duration: 5000,
            variant: 'left-accent' 
        })
    }
    
    return { addToast };
}

Then import the addToast method anywhere in your application import { addToast } from "../path/to/file";, create an instance const { addToast } = CustomToast(); and use it by passing a destructured object to the addToast function addToast({message: "sign in successful", type: "success"})... I hope this helps someone else out here.

等风也等你 2025-02-20 09:05:16

这是我的解决方案:我确实做了一个对象并使用了它:

const defaultToastProps = {
 position: "top-right" as ToastPosition,
 duration: 2000,
 isClosable: true,
};

const submitHandler = () => {
 Axios.post("/user/register", formData)
   .then((res) => {
     console.log(res);
     toast({
       title: "Account created.",
       description: "We've created your account for you.",
       status: "success",
       ...defaultToastProps,
     });
     nav("/login");
   })
   .catch((err) => {
     if (err.response) {
       console.log(err.response.data.message);
       toast({
         title: "Something went wrong.",
         description: err.response.data.message,
         status: "error",
         ...defaultToastProps,
       });
     } else {
       console.log(err);
       toast({
         title: "Something went wrong.",
         description: "server-error",
         status: "error",
         ...defaultToastProps,
       });
     }
   });
};

here is my solution: I did make an object and used it:

const defaultToastProps = {
 position: "top-right" as ToastPosition,
 duration: 2000,
 isClosable: true,
};

const submitHandler = () => {
 Axios.post("/user/register", formData)
   .then((res) => {
     console.log(res);
     toast({
       title: "Account created.",
       description: "We've created your account for you.",
       status: "success",
       ...defaultToastProps,
     });
     nav("/login");
   })
   .catch((err) => {
     if (err.response) {
       console.log(err.response.data.message);
       toast({
         title: "Something went wrong.",
         description: err.response.data.message,
         status: "error",
         ...defaultToastProps,
       });
     } else {
       console.log(err);
       toast({
         title: "Something went wrong.",
         description: "server-error",
         status: "error",
         ...defaultToastProps,
       });
     }
   });
};
梦境 2025-02-20 09:05:16

您可以使用React上下文API,

import { useToast } from '@chakra-ui/react'
import { createContext, useContext} from 'react'
const chatContext = createContext()

const ChatState = ({ children }) => {
    const toast = useToast()
   const Toast = (title, description, status, duration, position = 'top') => {
        return toast({
            title: title,
            description: description,
            status: status,
            duration: duration,
            isClosable: true,
            position: position,
        })
    }
 return (
        <chatContext.Provider value={{ Toast }}>{children}</chatContext.Provider>
    )
export const UseContextAPI = () => {
    return useContext(chatContext)
}
export default ChatState 

我是初学者,所以如果我在这里做错了什么,请纠正我。

You can use react context Api just like this,

import { useToast } from '@chakra-ui/react'
import { createContext, useContext} from 'react'
const chatContext = createContext()

const ChatState = ({ children }) => {
    const toast = useToast()
   const Toast = (title, description, status, duration, position = 'top') => {
        return toast({
            title: title,
            description: description,
            status: status,
            duration: duration,
            isClosable: true,
            position: position,
        })
    }
 return (
        <chatContext.Provider value={{ Toast }}>{children}</chatContext.Provider>
    )
export const UseContextAPI = () => {
    return useContext(chatContext)
}
export default ChatState 

I m beginner so please correct me if i have done something wrong here.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文