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

如何在NextJS中调整SVG图片的尺寸与颜色?

解决SVG组件样式不生效的问题

问题根源

  1. SVG文件本身带有硬编码的width/height或fill属性,导致CSS样式无法覆盖
  2. SVGR生成的组件可能未将className正确传递到根SVG元素

解决方案步骤

1. 修改SVG文件内容

打开headset.svg,调整两处关键配置:

  • 根SVG标签:保留viewBox属性(确保原始尺寸比例),移除固定的width/height值,或设置为100%
    示例:
    <!-- 修改前 -->
    <svg width="30" height="30" viewBox="0 0 30 30" ...>
    <!-- 修改后 -->
    <svg viewBox="0 0 30 30" width="100%" height="100%" ...>
    
  • 内部图形元素:将所有path/circle等元素的fill属性改为currentColor,让颜色继承组件的color样式
    示例:
    <!-- 修改前 -->
    <path fill="#000000" d="..." />
    <!-- 修改后 -->
    <path fill="currentColor" d="..." />
    

2. 优化SVGR的Webpack配置(可选)

确保SVGR生成的组件能接收并应用className,修改next.config.js:

module.exports = {
  webpack(config) {
    config.module.rules.push({
      test: /\.svg$/i,
      issuer: /\.[jt]sx?$/,
      use: [
        {
          loader: '@svgr/webpack',
          options: {
            template: (variables, { tpl }) => {
              return tpl`
                ${variables.imports};
                const ${variables.componentName} = (${variables.props}) => {
                  return ${variables.jsx};
                };
                export default ${variables.componentName};
              `;
            },
          },
        },
      ],
    });
    return config;
  },
};

3. 正常使用组件样式

现在可以通过Tailwind类直接控制尺寸和颜色:

import Logo from '../public/headset.svg';

// 组件内使用
<Logo className='w-[50px] h-[50px] text-black' />

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 19:17:22