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

React中:hover CSS效果失效求助:自定义Button组件hover不生效

问题原因及解决方案

你的问题出在React内联style属性不支持CSS伪类(如:hover)和嵌套选择器语法。React的style prop只能接受键值对形式的普通CSS属性,像&: hover这种类Sass/Less的写法完全不被识别,所以hover样式无法生效。另外你的代码存在语法错误:<Button>和<Theme>标签都未闭合,这会导致React渲染报错。

下面是几种可行的解决方法:

方法1:使用CSS类(推荐)

如果这个自定义Button组件支持传入className属性,直接通过CSS类定义hover样式是最简洁的方式:

  1. 新建CSS文件(比如App.css):
.custom-button {
  background: red;
}
.custom-button:hover {
  background: blue;
}
  1. 在组件中引入并使用:
import './App.css';

export default function App() {
  return (
    <Theme className="App">
      <Button
        label="My Button"
        iconLeft={IconAlert}
        size="m"
        className="custom-button"
      />
    </Theme>
  );
}

方法2:用React状态模拟hover效果

如果组件不支持className,可以通过监听鼠标事件切换状态来动态修改样式:

import { useState } from 'react';

export default function App() {
  const [isHovered, setIsHovered] = useState(false);

  const buttonStyle = {
    background: isHovered ? 'blue' : 'red'
  };

  return (
    <Theme className="App">
      <Button
        label="My Button"
        iconLeft={IconAlert}
        size="m"
        style={buttonStyle}
        onMouseEnter={() => setIsHovered(true)}
        onMouseLeave={() => setIsHovered(false)}
      />
    </Theme>
  );
}

方法3:使用CSS-in-JS库(如styled-components)

如果项目已经在用CSS-in-JS方案,可以用它来创建带hover样式的Button组件:

import styled from 'styled-components';

const StyledButton = styled(Button)`
  background: red;
  &:hover {
    background: blue;
  }
`;

export default function App() {
  return (
    <Theme className="App">
      <StyledButton
        label="My Button"
        iconLeft={IconAlert}
        size="m"
      />
    </Theme>
  );
}

内容的提问来源于stack exchange,提问作者Worker Raimir

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 19:22:31