反应从本地存储导入图像



如何在 react 中导入本地存储映像?

我的数据如下所示;

{ image:"newimage.jpeg" }

我试图这样做:

<img src={require("../../assets/images/`${data.image}`")}>

但它不起作用。任何建议将很高兴。

您只需要在文件路径周围使用反引号'':

<img src={require(`../../assets/images/${data.image}`)}>

require是特定于节点的IIRC - 您可能需要为React项目使用import(除非它以某种方式既是React又是Node)。

只需将图像作为模块导入即可。

从创建反应应用程序文档 (https://facebook.github.io/create-react-app/docs/adding-images-fonts-and-files):

import React from 'react';
import logo from './logo.png'; // Tell Webpack this JS file uses this image
console.log(logo); // /logo.84287d09.png
function Header() {
// Import result is the URL of your image
return <img src={logo} alt="Logo" />;
}
export default Header;

如果需要加载本地映像,它应位于公用文件夹中。 https://facebook.github.io/create-react-app/docs/using-the-public-folder#when-to-use-the-public-folder

您还可以导入要使用的图像。 https://facebook.github.io/create-react-app/docs/adding-images-fonts-and-files

最新更新