reactjs - 无法调整 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 在此链接 下
解决方案
我不相信您将能够像您尝试的那样覆盖任何样式。如果您查看文档,可能会清楚为什么:
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
并应用样式道具。
import { ReactComponent as SVG } from './icon.svg';
然后样式:
使用
style
道具<SVG style={{ fill: hover ? color : "#fff", width: "25px", height: "25px" }} />
使用 SVG 道具
<SVG fill={hover ? color : "#fff"} width={25} height={25} />
推荐阅读
- python - 如何在 Python 中转发套接字连接?
- typescript - Typescript 指定返回或函数类型不一样
- c# - ArcObjects:将要素类与多边形相交
- sql - 如何在 R 中过滤具有最新时间戳的行的数据表
- vim - 如何将标记带到屏幕中间?
- machine-learning - 使用机器学习的当前状态来解决以下提到的问题的最佳方法是什么?
- javascript - replaceWith() 不返回标签
- python - python & c-c++单元程序原因段
- javascript - 如何在具有相同 ID 的元素上分配 API 获取随机颜色?
- python - Python:如何跟踪列表的排序方式?