reactjs React - Snackbar作为全球组件( typescript )

bwitn5fc  于 2022-12-26  发布在  React
关注(0)|答案(1)|浏览(151)

首先祝你们大家圣诞快乐!
[React+类型脚本]
是的,我是react的新手,我更像是后端极客,但我们都需要学习新东西:)
我正在尝试让我的snackbar在所有组件中全局工作,而不是每次都写一个新的。
我以前看过一个关于这个的帖子:How to implement material-ui Snackbar as a global function?
但不幸的是我不能让它工作。
我的函数是否正确?如果正确,我现在如何从另一个组件调用它?
我做了这个函数:
SnackbarHOC.tsx
'

import { AlertTitle, IconButton, Snackbar } from '@mui/material';
import Slide from '@mui/material';
import Alert from '@mui/material';
import { useState } from 'react';
import CloseIcon from '@mui/icons-material/Close';

function SnackbarHOC<T>(WrappedComponent: React.ComponentType<T>, Alert: React.ElementType) {
    const [open, setOpen] = useState(false);
    const [message, setMessage] = useState("I'm a custom snackbar");
    const [duration, setDuration] = useState(2000);
    const [severity, setSeverity] = useState(
        "success"
    ); /** error | warning | info */

    return (props: T) => {

        const showMessage = (message: string, severity = "success", duration = 2000) => {
            setMessage(message);
            setSeverity(severity);
            setDuration(duration);
            setOpen(true);
        };

        const handleClose = (event: React.SyntheticEvent | Event, reason?: string) => {
            if (reason === 'clickaway') {
                return;
            }
        }

        return (
            <>
                <WrappedComponent {...props} snackbarShowMessage={showMessage} />
                <Snackbar
                    anchorOrigin={{
                        vertical: "bottom",
                        horizontal: "center"
                    }}
                    autoHideDuration={duration}
                    open={open}
                    onClose={handleClose}
                //TransitionComponent={Slide}
                >
                    <Alert severity="error"
                        sx={{ width: '100%' }}

                        action={
                            <IconButton
                                aria-label="close"
                                color="inherit"
                                size="small"
                                onClick={handleClose}>
                                <CloseIcon fontSize="inherit" />
                            </IconButton>
                        }>
                        {message}
                    </Alert>
                </Snackbar>
            </>
        );
    };
};

export default SnackbarHOC;

'
我试着从另一个组件调用它,但我现在不知道如何显示实际的snackbar:(。
这是所有没有给我的错误现在:
'

import SnackbarHOC from '../../SnackbarHOC';

'

gudnpqoy

gudnpqoy1#

我找到了一个解决方案,但在JS中基本上是一样的,我猜只是没有类型化。我正在NEXTJS中实现最新的

//index.jsx
import Head from 'next/head'
import { useState } from 'react';
import {Button} from '@mui/material'
import Notification from '../components/Notification.component'
//create the jsx file with the Snackbar component implemented

function Home() {
// we need a simple hook for the button
const [open, setOpen] = useState(false);
}
const handleClick = () => {
    setOpen(true);
};
const handleClose = (event, reason) => {
  if (reason === 'clickaway') {
    return;
  }

  setOpen(false);
};
return(
<div >
 <Head>
 <title>HOME</title>
 <meta name="description" content="AWESOME" />
 <link rel="icon" href="/favicon.ico" />
 </Head>

 <Button variant="outlined" onClick={handleClick}>SEND</Button>
{/*We can define new props for our component I'm mixin props from mui Alert and Snackbar, from Alert I'm using severity and from Snackbar the open and onClose and message goes inside the alert as a simple string :D */}
<Notification
          open={open}
          onClose={handleClose}
          severity="error"
          message="that is what I am talking about"/>
</div>
)

}

现在我们只需要创建一个自定义组件,其中包含多个lil组件,我们可以根据需要进行编辑!

//Notification.component.jsx file
import React, { forwardRef} from 'react';
import Snackbar from '@mui/material/Snackbar';
import MuiAlert from '@mui/material/Alert';

const Alert = forwardRef(function Alert(props, ref) {
  return <MuiAlert elevation={6} ref={ref} variant="filled" {...props} />;
});

const Notification= ({open, onClose, severity, message}) => {

  
/*<> ... </> The empty tag is shorthand for <React. Fragment>, allowing you to have multiple top-most elements without wrapping further HTML.
*/
  return (

    <>
      
      <Snackbar open={open} autoHideDuration={6000} onClose={onClose}>
        <Alert onClose={onClose} severity={severity} sx={{ width: '100%' }}>
          {message}
        </Alert>
      </Snackbar>
    </>
  );
}
export default Notification;

但是如果你真的想使用类型化的值,你可以在你的VSCode中检查每个变量和函数的返回类型,但是我真的看不出这有什么好处,但是因为它不会改变结果,所以我也不会在这里实现它。
我强烈推荐观看这个视频系列https://www.youtube.com/watch?v=Roxf91mp3kw&t=367s

相关问题