关于reactjs:Material-UI-如何将自定义Snackbar的过渡更改为Slide

Material-UI - How to change transition of Customized Snackbar to Slide

我想将Snackbar的过渡方式更改为Slide而不是Grow(默认行为),但是我无法做到这一点,因为我在Alert中使用了Snackbar。

这是Material-UI的原始演示:
https://codesandbox.io/s/e1dks

如果我导入此文件:

1
2
import Slide from '@material-ui/core/Slide';
import { TransitionProps } from '@material-ui/core/transitions';

创建此函数:

1
2
3
function SlideTransition(props: TransitionProps) {
  return <Slide {...props} direction="up" />;
}

并在Snackbar标签上插入此属性:

1
TransitionComponent={SlideTransition}

我有错误:
Cannot read property 'getBoundingClientRect' of null

当我尝试同时将Snackbar与Alert和Slide一起使用时,请查看错误
https://codesandbox.io/s/material-demo-ysub3

在https://material-ui.com/api/slide/上有一条警告可以提供帮助,但我不明白这一点:
A single child content element. a???? Needs to be able to hold a ref.

我正在使用带有Typescript的React。


看您的示例,控制台中出现错误:

1
Warning: Failed prop type: Invalid prop `children` supplied to `ForwardRef(Slide)`. Expected an element that can hold a ref. Did you accidentally use a plain function component for an element instead? For more information see https://material-ui.com/r/caveat-with-refs-guide

在"更多信息"链接之后,建议您将"普通功能组件"package在React.forwardRef中。

这导致将Alert函数从以下位置更改:

1
2
3
function Alert(props: AlertProps) {
  return <MuiAlert elevation={6} variant="filled" {...props} />;
}

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

进行此更改后,代码将按预期工作-警报从底部滑入而不是弹出视图。