@mantine/notifications 通知位置错乱怎么解决
【免费下载链接】mantineA fully featured React components library项目地址: https://gitcode.com/GitHub_Trending/ma/mantine
如果你在 Mantine 应用中已经渲染了Notifications组件,但通知没有出现在屏幕上配置的位置——position属性不生效、通知一直固定在页面底部——官方文档指出的原因是:没有导入@mantine/notifications包的样式。这篇文章按照文档给出的判断依据,说明如何确认并修复这个现象。
先确认现象是否一致
文档对“位置错乱”的描述是:通知在屏幕上的位置不正确,且通常伴随position属性不生效、通知卡住不动(stuck at the bottom)。如果你看到的就是上面截图里的效果,基本可以按这条路径修复;官方 x/notifications 文档 的“Do not forget to import styles”一节也提示,按安装步骤操作后若仍有异常,多半是漏导了通知样式。
前提:确认包已安装、组件放置正确
修复前先排除两个前置问题,否则加了样式位置也不会正确:
- 项目已安装
@mantine/notifications及其依赖包:
# With yarn yarn add @mantine/hooks @mantine/core @mantine/notifications # With npm npm install @mantine/hooks @mantine/core @mantine/notificationsNotifications组件渲染在MantineProvider内部:
import { MantineProvider } from '@mantine/core'; import { Notifications } from '@mantine/notifications'; function Demo() { return ( <MantineProvider> <Notifications /> {/* Your app here */} </MantineProvider> ); }文档对组件放置有两条要求:Notifications是普通组件而不是 provider,不需要用它包裹整个应用;也不要在应用中渲染多个Notifications组件,否则通知会被重复显示。
在应用根目录补上样式导入
官方修复方式是:在应用根部(入口文件)导入@mantine/notifications的样式,并且顺序上必须放在@mantine/core样式之后:
import '@mantine/core/styles.css'; // ‼️ import notifications styles after core package styles import '@mantine/notifications/styles.css';注意注释里强调的顺序:notifications 样式要紧跟在 core 样式之后导入,不要反过来。
验证修复结果
导入样式后,在应用里触发一条通知,检查位置是否恢复:
- 在
notifications.show/notifications.update中设置的position生效; - 如果调用时没有指定
position,则使用Notifications组件的position属性值。例如:
import { Notifications } from '@mantine/notifications'; function Demo() { return <Notifications position="top-right" zIndex={1000} />; }文档说明此时通知会显示在屏幕右上角。position支持的取值为:top-left、top-right、top-center、bottom-left、bottom-right、bottom-center。
当通知不再固定在页面底部、并按上述取值出现在对应角落时,问题即已解决。
相关文档
- 现象说明与成因:notifications-missing-styles.mdx
@mantine/notifications安装、用法与position说明:notifications.mdx- 包安装命令:README
【免费下载链接】mantineA fully featured React components library项目地址: https://gitcode.com/GitHub_Trending/ma/mantine
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考