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

如何在React中结合Styled Components使用SVG?Vite环境报错解决

解决Vite + SVGR + Styled Components构建SVG组件的问题

1. 确认SVGR插件的正确配置

首先确保安装的是@svgr/vite(Vite官方适配的SVGR插件),然后在vite.config.js中添加插件配置:

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import svgr from '@svgr/vite'

export default defineConfig({
  plugins: [
    react(),
    svgr({
      exportType: 'named', // 确保导出包含ReactComponent
      svgoConfig: {
        plugins: [{ removeViewBox: false }] // 保留viewBox避免缩放异常
      }
    })
  ]
})

2. 修正SVG导入语句

修改LikeButton.jsx中的导入路径,使用?react后缀(Vite中SVGR插件的默认触发标识),替换原有的?import:

import { ReactComponent as HeartIcon } from '../assets/icons/heart.svg?react'
import styled from 'styled-components'

3. 结合Styled Components封装SVG组件

直接对导入的React SVG组件进行样式封装,支持动态属性控制样式:

const StyledHeartIcon = styled(HeartIcon)`
  width: 24px;
  height: 24px;
  fill: ${props => props.isLiked ? '#ff4d4f' : '#ccc'};
  cursor: pointer;
  transition: fill 0.2s ease;

  &:hover {
    fill: ${props => props.isLiked ? '#ff7875' : '#999'};
  }
`

const LikeButton = ({ isLiked, onClick }) => {
  return (
    <StyledHeartIcon
      isLiked={isLiked}
      onClick={onClick}
    />
  )
}

export default LikeButton

4. 在Test组件中正常引入使用

import LikeButton from './LikeButton'
import { useState } from 'react'

const Test = () => {
  const [liked, setLiked] = useState(false)

  return (
    <div>
      <LikeButton 
        isLiked={liked} 
        onClick={() => setLiked(!liked)} 
      />
    </div>
  )
}

export default Test

常见问题排查

  • 若之前使用的是旧版vite-plugin-svgr,建议替换为官方维护的@svgr/vite,两者配置逻辑存在差异
  • 检查SVG文件本身是否存在语法错误(如未闭合标签)
  • 重启Vite开发服务器,避免缓存导致配置未生效

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 08:57:13