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

React中SVG样式处理:悬停按钮时修改TSX组件fill属性为#FFF

实现按钮悬停时SVG填充色切换

以下是两种可行的实现方案:

方案一:利用styled-components后代选择器(推荐)

这种方式通过CSS后代选择器直接在按钮的hover状态下控制内部SVG的样式,无需额外状态管理,更简洁。

首先要确保你的ArrowIcon TSX组件支持接收className属性,并将其传递给底层的<svg>标签:

const ArrowIcon = ({ fill, className }: { fill?: string; className?: string }) => {
  return (
    <svg className={className} fill={fill} /* 此处保留你的SVG路径及其他属性 */>
      {/* SVG内部元素 */}
    </svg>
  );
};

接下来修改Btn的styled样式,在hover状态下添加对ArrowIcon的样式控制:

const Btn = styled.button`
  background-color: ${({ theme }) => theme.colors.basic.green};
  width: 100%;
  border: none;
  font-family: "JetBrains Mono", monospace;
  font-size: ${({ theme }) => theme.typography.fontSize.small};
  color: ${({ theme }) => theme.colors.basic.cardsBackgroundColor};
  padding: 20px 0;
  display: flex;
  gap: 24px;
  justify-content: center;
  align-items: center;
  font-weight: ${({ theme }) => theme.typography.fontWeight};

  &:hover {
    cursor: pointer;
    background-color: ${({ theme }) =>
      theme.colors.button.hoverBackgroundColor};
    border: solid 1px ${({ theme }) => theme.colors.button.hoverBorderColor};
    color: ${({ theme }) => theme.colors.button.hoverColor};

    /* 新增:鼠标悬停时改变SVG填充色 */
    ${ArrowIcon} {
      fill: #FFF;
    }
  }
`;

你的Button组件代码可以保持原样:

function Button() {
  const context = useContext(myContext);

  return (
    <Btn onClick={() => context.setNewPassword(context.generatedpassword)}>
      Generate
      <ArrowIcon fill="#24232C" />
    </Btn>
  );
}

方案二:通过React状态控制填充色

如果需要更灵活的逻辑控制,可以通过状态追踪按钮的hover状态,再将填充色属性传递给SVG组件:

import { useState } from 'react';

function Button() {
  const context = useContext(myContext);
  const [isBtnHovered, setIsBtnHovered] = useState(false);

  return (
    <Btn 
      onClick={() => context.setNewPassword(context.generatedpassword)}
      onMouseEnter={() => setIsBtnHovered(true)}
      onMouseLeave={() => setIsBtnHovered(false)}
    >
      Generate
      <ArrowIcon fill={isBtnHovered ? "#FFF" : "#24232C"} />
    </Btn>
  );
}

这种方式不需要修改styled样式,但需要手动处理鼠标进入/离开事件。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 00:26:34