【问题标题】:Pass function component context as parameter in React在 React 中将函数组件上下文作为参数传递
【发布时间】:2021-09-29 23:13:16
【问题描述】:

我正在使用notistack,它的用法很简单:

const { enqueueSnackbar } = useSnackbar();
enqueueSnackbar('text')

这需要在函数组件内运行,因为useSnackbar 本身就是一个钩子。

我想围绕它创建一个简单的界面并导出函数以在函数组件中使用:

import { useSnackbar } from 'notistack';

const toast = function () {
  const { enqueueSnackbar } = useSnackbar();
  enqueueSnackbar(arguments)
}
const toastOptions = {
  anchorOrigin: {
    vertical: 'top',
    horizontal: 'right',
  }
}
const alert = (text) => toast(text, { variant: 'alert', ...toastOptions });
const warn = (text) => toast(text, { variant: 'warning', ...toastOptions });
const info = (text) => toast(text, { variant: 'info', ...toastOptions });
const success = (text) => toast(text, { variant: 'success', ...toastOptions });

export { alert, warn, info, success }

但这失败了,因为Hooks can only be called inside of the body of a function component

有没有办法将函数组件上下文作为参数传递?尝试传递 this 并尝试传递 this.call(toast...) 或类似的,但 this 在函数组件中未定义。

【问题讨论】:

  • 你可以在你的函数 alert、warn、info、success 中添加第二个参数 enqueueSnackbar,并在你的组件内部调用你的钩子 useSnackbar。

标签: reactjs react-hooks jsx


【解决方案1】:

您可以通过在自定义挂钩中使用 useSnackbar 来解决Hooks can only be called inside of the body of a function component 的问题:

import { useSnackbar } from "notistack";

const toastOptions = {
  anchorOrigin: {
    vertical: "top",
    horizontal: "right"
  }
};

export function useToast() {
  const { enqueueSnackbar } = useSnackbar();
    
  const alert = (text) => enqueueSnackbar(text, { variant: "alert", ...toastOptions });
  const warn = (text) => enqueueSnackbar(text, { variant: "warning", ...toastOptions });
  const info = (text) => enqueueSnackbar(text, { variant: "info", ...toastOptions });
  const success = (text) =>
    enqueueSnackbar(text, { variant: "success", ...toastOptions });

  return { alert, warn, info, success };
}

在你的组件内部:

export const MyComponent () => {
   const { alert, warn, info, success } = useToast()
   //......
};

【讨论】:

    猜你喜欢
    • 2020-05-23
    • 2022-11-20
    • 2019-10-18
    • 2019-12-05
    • 2021-02-23
    • 2012-12-16
    • 2010-10-01
    • 2011-02-20
    • 1970-01-01
    相关资源
    最近更新 更多