如何在img src中指定要在react/JavaScript中加载的图像本地路径



假设我必须从本地路径拍摄图像&路径值来自API,我将该路径设为常量,并尝试将该路径添加到我的图像src中以显示在页面上。

示例:

import React, {Component} from 'react';
class ImageElement extends Component {
static displayName = 'ImageElement';
render() {
const {element:{defaultPath, height, width}} = this.props;
const imagePath = 'E:/myPic/IMG_20191221_204716.jpg';
return (
<div>
<img
src={imagePath}
height={height}
width={width}
/>
</div>
);
}
}
export default ImageElement;

Chrome正在抛出一个错误,如不允许加载本地资源:file:///E:/myPic/IMG_20191221_204716.jpg

我已经尝试了其他用户建议的不同选项,如

  1. 跨越本地服务器,然后尝试访问文件
  2. c: \Program Files(x86(\谷歌\铬\应用程序\铬.exe--允许从文件访问文件

第一个选项有效,但在我的用例中没有用处第二个根本不起作用。还尝试安装一些插件,但都不起作用。

欢迎提供任何进一步的指导。

不确定我是否能很好地恢复你的pb,但我认为你应该将文件添加到你的项目src文件夹或其他地方,并导入类似图像的组件:

import imagePath from "./assets/img/IMG_20191221_204716.jpg";

最新更新