首页 > 解决方案 > 无法调整 SVG 元素的大小

问题描述

我一直在尝试调整我已导入到我的 react 项目中的这个 svg 元素的大小,但在多种方式上都没有运气

我导入 SVG

import SVG from "../icon.svg"

然后将其用作 inline-svg

我试过

<SVG
  style={{
    fill: hover ? color : "#fff",
    width="25px" // first method
    height="25px" // first method
  }}
  viewBox="0 0 25 25" // second method
  width="25" // third method
  height="25" // third method
/>

也尝试了所有这些都没有运气

我还尝试通过其容器来限制 svg 大小,但运气不好

父 svg 元素已调整大小,但其路径在外部溢出,并且未使用提供的值正确调整大小

我最接近正常的方法是当我将高度设置为 1-5 之类的低数字但无论如何它都会剪辑图标

我也在使用 babel-plugin 导入 svg 图像作为反应组件

我在这里做错了什么?

我正在使用的 svg 在此链接

标签: reactjssvgnext.js

解决方案


我不相信您将能够像您尝试的那样覆盖任何样式。如果您查看文档,可能会清楚为什么:

babel-plugin-inline-react-svg

将 SVG 文件的导入转换为 React 组件,并使用 SVGO 优化 SVG。

例如,下面的代码...

import React from 'react';
import CloseSVG from './close.svg';

const MyComponent = () => <CloseSVG />;

会变成……

import React from 'react';
const CloseSVG = () => <svg>{/* ... */}</svg>;

const MyComponent = () => <CloseSVG />;

const CloseSVG = () => <svg>{/* ... */}</svg>;不允许向 JSX 传递额外的 props

建议一

可以创建一个将 CSS 样式应用于嵌套svg标签的包装器。

使用示例styled-components

import styled from "styled-components";

const SvgWrapper = styled.div`
  svg {
    fill: ${({ fill }) => fill};
    height: ${({ height }) => height};
    width: ${({ width }) => width};
  }
`;

<SvgWrapper height="25px" width="25px" fill="pink">
  <SvgIcon />
</SvgWrapper>

建议二

将 SVG 图像导入为 aReactComponent并应用样式道具。

添加 SVG

import { ReactComponent as SVG } from './icon.svg';

然后样式:

  1. 使用style道具

    <SVG
      style={{
        fill: hover ? color : "#fff",
        width: "25px",
        height: "25px"
      }}
    />
    
  2. 使用 SVG 道具

    <SVG
      fill={hover ? color : "#fff"}
      width={25}
      height={25}
    />
    

编辑无法调整大小的SVG元素(分叉)

在此处输入图像描述


推荐阅读