如何导出 useContext 变量而不必在每个组件上调用 useContext?

Posted

技术标签:

【中文标题】如何导出 useContext 变量而不必在每个组件上调用 useContext?【英文标题】:How to export a useContext variable without having to call useContext on each components? 【发布时间】: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("")
   ...

【问题讨论】:

【参考方案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 并且需要在提供程序的末尾附加一个组件,而不仅仅是纯全局函数。谢谢你的回答。

以上是关于如何导出 useContext 变量而不必在每个组件上调用 useContext?的主要内容,如果未能解决你的问题,请参考以下文章