[英]How do I load an image from my project folder inside a JavaScript file?
I am trying to build a website and I currently am using a data.js file to be the source of images and links in one of my components.我正在尝试建立一个网站,目前我正在使用 data.js 文件作为我的一个组件中图像和链接的来源。 The file structure looks like this right now.
文件结构现在看起来像这样。
And my data.js file looks something like this:我的 data.js 文件看起来像这样:
export const products = [
{
id: 1,
img: "",
link: "http://lama.dev",
},
{
id: 2,
img: "",
link: "http://lama.dev",
},
];
I wish to use the images under my 'img' folder to be inside the img: "xxx"
part but I am unsure how.我希望将我的“img”文件夹下的图像用于
img: "xxx"
部分,但我不确定如何使用。 Is this even possible?这可能吗?
Not sure if this is needed but this is how I intend to use my data.js file:不确定是否需要这样做,但这就是我打算使用我的 data.js 文件的方式:
import "./product.css";
const Product = ({ img, link }) => {
return (
<div className="p">
<div className="p-browser">
<div className="p-circle"></div>
<div className="p-circle"></div>
<div className="p-circle"></div>
</div>
<a href={link} target="_blank" rel="noreferrer">
<img src={img} alt="" className="p-img" />
</a>
</div>
);
};
export default Product;
you can import your image from your img folder like this.您可以像这样从您的 img 文件夹中导入图像。
import FirstImg from "./img/pexels-cátia-matos-1072179.jpg";
and you can use like this in same file你可以在同一个文件中这样使用
export const products = [
{
id: 1,
img: FirstImg,
link: "http://lama.dev"
}
];
or或者
You can change your img folder location to public您可以将您的 img 文件夹位置更改为公共
public/img公共/img
and you can use like this你可以这样使用
export const products = [
{
id: 1,
img: "./img/470a19a36904fe200610cc1f41eb00d9.jpg",
link: "http://lama.dev"
}
];
Try this in your data.js在你的 data.js 中试试这个
import figma from './me.jpg'
export const products = [
{
id: 1,
img: figma,
link: "http://lama.dev",
},
{
id: 2,
img: "",
link: "http://lama.dev",
},
];
You can move your images folder under public directory.您可以将图像文件夹移动到公共目录下。 Otherwise all those images would be bundled when you create your react app.
否则,当您创建 React 应用程序时,所有这些图像都将被捆绑。
You can then make your data.js to然后你可以让你的 data.js 到
const products = [
{
id: 1,
img: '/img/image.jpg',
link: 'http://file/'
}
]
export default products
use require
method in js在js中使用
require
方法
const products = [
{
id: 1,
img: require('/img/image.jpg'),
link: 'http://file/'
}
]
export default products
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.