【问题标题】:Can not find local images找不到本地图片
【发布时间】:2016-08-02 19:02:59
【问题描述】:

我有一个用 React 和 Django 构建的项目。我也在使用 Webpack 来加载更改。我想显示本地驱动器中的图像。

我要显示照片的文件位于:

myProject/brandplug/static/app/photoGrid/SampleDisplay.jsx

照片位于:

myProject/brandplug/static/location_photos/

index.jsx 文件位于:

myProject/brandplug/static/app/index.jsx

渲染 React 的 html 文件位于:

myProject/accounts/templates/index.html

所以我从SampleDisplay.jsx 尝试导入这样的图像:

const itemStyle = {
  backgroundImage: `{require("../location_photos/" + ${photoName})}`
};

然后:

<div style={itemStyle}>
</div>

我也尝试使用"../../location_photos/""../../brandplug/static/location_photos/",而不是"../location_photos/"

但是,图像仍未加载。

如何加载它们?

【问题讨论】:

  • 使用前需要先获取图片。在webpack 你应该需要文件然后使用它,因为我看到你正在尝试通过名称动态地需要文件。你需要做这样的事情jsfiddle.net/6uLLus9v/1
  • 但是我需要它,如上图。
  • 你不能像你那样做。 webpack 在构建过程之前需要 require 文件,并且不能动态加载文件

标签: javascript django reactjs webpack


【解决方案1】:

您只是将 backgroundImage 设置为一个字符串,它恰好与 require 的语法相同。

您可以要求图像并使用它:

const itemStyle = {
    backgroundImage: {require(`../location_photos/${photoName}`)}
};

但我从未尝试过。您可能会发现THIS SO 问题很有用。

我建议你不要尝试使用 webpack 来加载图像,而是让 Django 来提供它。

const itemStyle = {
    backgroundImage: `url("/static/location_photos/${photoName}")}`
};

假设您已将静态文件设置为托管在 /static/

另外,你稍微误用了反引号字符串模板,也就是说,你不需要 +:

`{require("../location_photos/${photoName}")}`

【讨论】:

    猜你喜欢
    • 2012-04-19
    • 2013-03-27
    • 2019-05-04
    • 2012-01-12
    • 2013-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-21
    相关资源
    最近更新 更多