You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Mantine(v7)按钮悬停颜色覆盖失效问题求助

Mantine v7 Button 自定义悬停背景色不生效的解决方法

这是因为Mantine v7的状态样式机制和旧版本不同,直接用:hover伪类会被框架内置样式覆盖,解决方法如下:

推荐方案:使用Mantine内置的状态数据属性

Mantine v7通过data-hovered这类数据属性来管理组件状态,用它替代:hover伪类可以保证样式优先级足够:

import React from "react";
import ReactDOM from "react-dom/client";
import { MantineProvider, Button } from "@mantine/core";

ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render(
  <MantineProvider>
    <React.StrictMode>
      <Button
        size="md"
        styles={{
          root: {
            backgroundColor: 'blue',
            '&[data-hovered]': {
              backgroundColor: 'red',
            },
          },
        }}
      >
        TEST BUTTON
      </Button>
    </React.StrictMode>
  </MantineProvider>
);

备选方案:提升样式优先级(不推荐)

如果一定要用:hover伪类,可以通过!important强制提升样式优先级,但这种方式会破坏样式的可维护性,不建议在生产环境使用:

import React from "react";
import ReactDOM from "react-dom/client";
import { MantineProvider, Button } from "@mantine/core";

ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render(
  <MantineProvider>
    <React.StrictMode>
      <Button
        size="md"
        styles={{
          root: {
            backgroundColor: 'blue',
            '&:hover': {
              backgroundColor: 'red !important',
            },
          },
        }}
      >
        TEST BUTTON
      </Button>
    </React.StrictMode>
  </MantineProvider>
);

原因说明

Mantine v7重构了组件样式系统,默认的状态样式(如悬停、激活)都是通过数据属性来定义的,这些样式的CSS特异性比普通的:hover伪类更高,所以直接自定义:hover样式会被框架内置样式覆盖。而旧版本Mantine依赖伪类来管理状态,所以当时的写法能生效。

内容的提问来源于stack exchange,提问作者Eleanor Scerri

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 20:09:58