首页 > 解决方案 > 如何在 SnackbarProvider 的内容中获取变量值

问题描述

我正在使用notistacksnackbar在我的应用程序中显示。我想自定义小吃吧的内容。因此使用content的属性snackbar。我想知道消息变体是successor warningor error,并且基于此我想设置颜色。吐司。下面是一个沙盒 URL: https ://codesandbox.io/s/optimistic-hellman-2gcs0?file=/App.js

我怎样才能得到里面的变量值ToastTemplate

标签: reactjsreact-reduxmaterial-uisnackbar

解决方案


在你的export const enqueueSnackbar = (notification) => {函数里面你有一个notification对象,它有你可以使用的optionsvariant

export const enqueueSnackbar = (notification) => {
    const key = notification.options && notification.options.key;
    const variant = notification.options && notification.options.variant;
    console.log(variant);

    console.log(notification);
    return {
        type: ENQUEUE_SNACKBAR,
        notification: {
            ...notification,
            key: key || new Date().getTime() + Math.random(),
        },
    };
};

更新

由于您想在内部进行变体SnackbarProvider,因此您可以传递整个数据(而不仅仅是文本消息)并在内部使用您需要的内容。

export const enqueueSnackbar = notification => {
  const key = notification.options && notification.options.key;
  return {
    type: ENQUEUE_SNACKBAR,
    notification: {
      message: { ...notification },
      // ^ Instead of passing the text - I'm passing the entire object
      key: key || new Date().getTime() + Math.random()
    }
  };
};

在 SnackbarProvider 内部:

<SnackbarProvider
  content={(key, notificationData) => {
    const message = notificationData.message;
    const variant = notificationData.options.variant
    console.log(variant);
    return <ToastTemplate id={key} message={message} />;
  }}
>

在此处查看工作示例:https ://codesandbox.io/s/flamboyant-ramanujan-1p7yw?file=/index.js


推荐阅读