【发布时间】: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