React.js 样式组件导入图像并将它们用作 div 背景 [英] React.js styled-components importing images and using them as div background
问题描述
我正在使用样式组件并尝试设置像这样的背景图像
I am using styled-components and am trying to set a background image like so
const HeaderImage= styled.div`
background-image: url('../../assets/image.png');
';
我也试过不加引号,就像这样
I've also tried without the quotes, like so
const HeaderImage= styled.div`
background-image: url(../../assets/image.png);
';
在这两种情况下,我得到相同的结果
In both cases, I get the same result
http://localhost:3000/assets/image.png 加载资源失败:服务器响应状态为 404(未找到)
http://localhost:3000/assets/image.png Failed to load resource: the server responded with a status of 404 (Not Found)
我正在使用 Richard Kall 的 react starter
文件肯定在指定位置.
我加载错误了吗?
我应该提一下,我对此很陌生(React 和样式组件)
I should mention, I'm very new to this (React, and styled-components)
推荐答案
你应该按照以下方式导入图片(假设你已经配置了 webpack 来导入媒体资源).
You should import images in the following manner (assuming that you have webpack configured for importing media assets).
import myImage from '../../assets/image.png';
/* ... */
const HeaderImage = styled.div`
background-image: url(${myImage});
`;
这篇关于React.js 样式组件导入图像并将它们用作 div 背景的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!