React中SVG作为CSS背景图无法显示的问题求助
解决SVG作为CSS背景图不显示的问题
1. 给SVG添加填充色
你的SVG路径未设置填充色,默认处于透明状态,即便加载成功也无法看到。修改SVG代码,给<path>标签添加fill属性:
<svg version="1.1" xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"> <path fill="#000000" d="M13.25 10l-7.141-7.42c-0.268-0.27-0.268-0.707 0-0.979 0.268-0.27 0.701-0.27 0.969 0l7.83 7.908c0.268 0.271 0.268 0.709 0 0.979l-7.83 7.908c-0.268 0.271-0.701 0.27-0.969 0s-0.268-0.707 0-0.979l7.141-7.417z"></path> </svg>
2. 完善CSS背景控制属性
当前CSS仅设置了宽高和背景图,缺少控制背景显示的关键属性,补充以下内容:
&__item::before { content: ""; height: 2rem; width: 2rem; margin-right: .7rem; background-image: url(../img/SVG/chevron-thin-right.svg); /* 新增必要属性 */ background-size: contain; background-repeat: no-repeat; background-position: center; display: inline-block; /* 确保伪元素宽高生效 */ }
3. 验证文件路径正确性
React项目中,CSS里的相对路径是相对于CSS文件所在位置的:
- 若CSS文件在
src/components/Nav/Nav.module.css,SVG在src/img/SVG/chevron-thin-right.svg,路径需调整为url('../../img/SVG/chevron-thin-right.svg') - 也可将SVG放入
public/img/SVG/目录,使用绝对路径:url('/img/SVG/chevron-thin-right.svg')(public目录下资源可直接通过根路径访问)
4. 模块导入方式引用SVG(推荐)
在React中,用模块导入SVG更可靠:
- 在组件文件中导入SVG:
import ChevronRight from '../img/SVG/chevron-thin-right.svg';
- 配合CSS Modules使用:
&__item::before { content: ""; height: 2rem; width: 2rem; margin-right: .7rem; background-image: url(${ChevronRight}); background-size: contain; background-repeat: no-repeat; background-position: center; display: inline-block; }
若使用普通CSS,可通过内联样式实现:
const navItemStyle = { '&::before': { content: '""', height: '2rem', width: '2rem', marginRight: '.7rem', backgroundImage: `url(${ChevronRight})`, backgroundSize: 'contain', backgroundRepeat: 'no-repeat', backgroundPosition: 'center', display: 'inline-block' } };
内容的提问来源于stack exchange,提问作者Amadeus
相关产品推荐
相关产品推荐

