【问题标题】:How to export a useContext variable without having to call useContext on each components?如何导出 useContext 变量而不必在每个组件上调用 useContext?
【发布时间】:2021-12-01 19:21:18
【问题描述】:

我编写了一个 toast 上下文并将整个项目包装在 toast 提供程序中。如果我的某个组件需要使用 toast,它会调用

function Component() {
   const toast = useToast();
   toast.success("")
   ...
}

有没有办法直接导入 toast 而不必在单个组件上调用 useToast() 如下?

import { toast } from "./toast-provider.tsx"

function Component() {
   toast.success("")
   ...
}

【问题讨论】:

    标签: reactjs react-context react-functional-component


    【解决方案1】:

    我假设您的 toast 类似于 <React.createContext().Provider />。

    在这种情况下,不能拨打toast.attribute,至少根据我的理解。您必须为类使用高阶组件,在您的情况下,使用 useContext 挂钩或类似的功能组件。

    如果您希望能够使用点符号访问 toast 的属性,则 toast 必须是例如一个东西。这是创建上下文的一种可能性:

    function getAttr2() {
      return "some dynamic value";
    }
    
    export const toast = {
      attribute1: "some attribute",
      attribute2: getAttr2()
    };
    

    但这当然不符合 React 使用上下文的方式。

    【讨论】:

    • 我的 useToast 基本上是“export const useToast = () => useContext(ToastContext);”。不过,您的建议在我的情况下不起作用,因为我的 toast 提供程序使用 react-toastitfy 并且需要在提供程序的末尾附加一个组件,而不仅仅是纯全局函数。谢谢你的回答。
    猜你喜欢
    • 1970-01-01
    • 2021-06-19
    • 1970-01-01
    • 1970-01-01
    • 2022-11-24
    • 1970-01-01
    • 2020-03-10
    • 1970-01-01
    • 2020-10-24
    相关资源
    最近更新 更多