如何根据antd notification的类型动态修改通知组件文本颜色?
问题原因
你在style中配置的样式仅作用于通知组件的最外层容器,antd 内部对通知标题、描述文本单独设置了默认颜色样式,优先级高于外层容器的继承样式,因此直接在外层设置color属性无法生效。
解决方案
方案1:直接包裹内容节点(零额外配置,适配现有代码)
不需要额外写CSS,直接给message和description字段传入带内联样式的React节点即可,修改后的完整代码如下:
import { notification } from "antd"; const openNotification = (title, message, type) => { const textColor = type === "error" ? "red" : "white"; notification[type]({ message: <span style={{ color: textColor }}>{title}</span>, description: <span style={{ color: textColor }}>{message}</span>, style: { backgroundColor: type === "error" ? "red" : "white" }, duration: 0, }); }; export default openNotification;
提示:你当前配置非error类型的通知背景为白色,搭配白色文本会导致内容不可见,建议对应调整非error类型的背景色为深色。
方案2:自定义类名覆写默认样式(适合全局统一管控场景)
如果不想每次调用都包裹内容节点,可以给通知添加自定义类名,通过CSS覆写antd内置的文本样式:
- 调用通知时新增
className配置:
import { notification } from "antd"; const openNotification = (title, message, type) => { notification[type]({ message: title, description: message, className: `custom-notice custom-notice-${type}`, style: { backgroundColor: type == "error" ? "red" : "white" }, duration: 0, }); }; export default openNotification;
- 在全局样式文件中添加覆写规则:
/* error类型文本设为红色 */ .custom-notice-error .ant-notification-notice-message, .custom-notice-error .ant-notification-notice-description { color: red !important; } /* 其余类型文本设为白色 */ .custom-notice:not(.custom-notice-error) .ant-notification-notice-message, .custom-notice:not(.custom-notice-error) .ant-notification-notice-description { color: white !important; }
内容的提问来源于stack exchange,提问作者Abdullah Abbasi
相关产品推荐
相关产品推荐

