问题
I am using Material-UI
for the first time and trying to implement Snackbar
on success of an API post. I want the Snackbar to slide up onEnter and then slide down onExit. I was able to implement slide up onEnter but need help for "Slide down onExit". Can anyone help me?
import React, { useState } from "react";
import Snackbar from "@material-ui/core/Snackbar";
import Slide from "@material-ui/core/Slide";
const [openSnackBar, setOpenSnackBar] = useState(false);
const renderSnackbar = () => {
return (
<Snackbar
id="id-success-snackbar"
className="success-snackbar"
anchorOrigin={{
vertical: "bottom",
horizontal: "left"
}}
open={openSnackBar}
autoHideDuration={5000}
onClose={() => setOpenSnackBar(false)}
TransitionComponent={Slide}
message="Test Message"
/>
);
};
回答1:
You'll need to set TransitionComponent
to a function that takes TransitionProps
as its parameter and returns the Slide
transition with those props spread onto it. From the Material UI docs here in the "Change Transition" section, notice that the examples given render the Slide
transition component as such:
function SlideTransition(props: TransitionProps) {
return <Slide {...props} direction="up" />;
}
That's because the TransitionComponent
prop of Snackbar
takes in a callback of the same signature and applies the slide up animation to the snackbar this way.
Your code snippet should thus look something like this:
import React, { useState } from "react";
import Snackbar from "@material-ui/core/Snackbar";
import Slide from "@material-ui/core/Slide";
const [openSnackBar, setOpenSnackBar] = useState(false);
const renderSnackbar = () => {
return (
<Snackbar
id="id-success-snackbar"
className="success-snackbar"
anchorOrigin={{
vertical: "bottom",
horizontal: "left"
}}
open={openSnackBar}
autoHideDuration={5000}
onClose={() => setOpenSnackBar(false)}
/* set this to the function below */
TransitionComponent={slideTransition}
message="Test Message"
/>
);
};
// Function that should be passed to the TransitionComponent prop above
const slideTransition = (props: TransitionProps) => {
return <Slide {...props} direction="up" />;
};
I too have found through my own experimentation that simply putting <Slide />
or Slide
in the prop allows the snackbar to animate onEnter, but not onExit. I hope this helps you or others who may have a similar problem.
来源:https://stackoverflow.com/questions/59440683/material-uis-snackbar-is-not-sliding-down