简体   繁体   English

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

[英]How to specify image local path in img src to load in react/JavaScript

Suppose I have to take an image from my local path & the path value is coming from API and I have taken that path in constant and trying to add that path in my image src to show on the page.假设我必须从我的本地路径中获取图像并且路径值来自 API 并且我已经采用了该路径并尝试在我的图像 src 中添加该路径以显示在页面上。

Example:例子:

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 is throwing an error like Not allowed to load local resource: file:///E:/myPic/IMG_20191221_204716.jpg Chrome 会抛出一个错误,例如Not allowed to load local resource: file:///E:/myPic/IMG_20191221_204716.jpg

I have tried different options as suggested by other users like我尝试了其他用户建议的不同选项,例如

  1. Spanning a local server and then try to access file then跨越本地服务器,然后尝试访问文件
  2. c:\Program Files (x86)\google\chrome\Application\chrome.exe --allow-file-access-from-files c:\Program Files (x86)\google\chrome\Application\chrome.exe --allow-file-access-from-files

The first option works but is not useful in my use case the second one doesn't work at all.第一个选项有效,但在我的用例中没有用,第二个根本不起作用。 also tried installing some plugin and all do not work.还尝试安装一些插件,但都不起作用。

Any further guidance is appreciated.任何进一步的指导表示赞赏。

not sure if im undrestood well ur pb but i think u should add file to ur project src folder or somewhere and import image like component:不确定我是否很好地恢复了你的 pb,但我认为你应该将文件添加到你的项目 src 文件夹或某处并导入像组件这样的图像:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM