Skip to content

Instantly share code, notes, and snippets.

@Houserqu
Last active May 5, 2021 01:38
Show Gist options
  • Save Houserqu/abdd6e5161861a2b145d21239f23f62c to your computer and use it in GitHub Desktop.
Save Houserqu/abdd6e5161861a2b145d21239f23f62c to your computer and use it in GitHub Desktop.
material-ui

material-ui 组件库的消息通知组件的封装,可以在任何地方调用 参考

思路:snackbar 以组件的形式注册后,子自己通过props调用,这里暴露出组件的 ref 从而使用 props 触发

import { useSnackbar, VariantType, WithSnackbarProps } from 'notistack'
import React from 'react'

interface IProps {
  setUseSnackbarRef: (showSnackbar: WithSnackbarProps) => void
}

const InnerSnackbarUtilsConfigurator: React.FC<IProps> = (props: IProps) => {
  props.setUseSnackbarRef(useSnackbar())
  return null
}

let useSnackbarRef: WithSnackbarProps
const setUseSnackbarRef = (useSnackbarRefProp: WithSnackbarProps) => {
  useSnackbarRef = useSnackbarRefProp
}

export const SnackbarUtilsConfigurator = () => {
  return <InnerSnackbarUtilsConfigurator setUseSnackbarRef={setUseSnackbarRef} />
}

export default {
  success(msg: string, options: OptionsObject = {}) {
    this.toast(msg, { ...options, variant: 'success' })
  },
  warning(msg: string, options: OptionsObject = {}) {
    this.toast(msg, { ...options, variant: 'warning' })
  },
  info(msg: string, options: OptionsObject = {}) {
    this.toast(msg, { ...options, variant: 'info' })
  },
  error(msg: string, options: OptionsObject = {}) {
    this.toast(msg, { ...options, variant: 'error' })
  },
  toast(msg: string, options: OptionsObject = {}) {
    useSnackbarRef.enqueueSnackbar(msg, options)
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment