Visual Studio反应图像路径无法达到

乔什·温特斯(Josh Winters)

所以我有一个用react.js创建的Visual Studio项目。

我试图动态链接到图像,但是失败了。这是我正在尝试的代码:

在顶部,我为路径的第一部分设置了一个变量:

this.LogoPath = '../images/'

然后,我会通过api调用动态获取图像的名称。

this.setState({ imageNamePath: this.state.location.imageName })

然后将它们隐喻为:

{`${this.LogoPath}${this.state.location.imageName}`}

在控制台中,即时通讯:

img src='../images/the-images-name-here.png'

因此,它似乎有效,但事实并非如此。我没有任何错误,并且图像损坏。我最好的猜测是反应将图像更改为:

image-name-here.6a131799.png

肯定有人遇到过这个问题,但是我的Google搜索几乎没有帮助。

那么我如何显示图像呢?

拉杜·尼梅伦科(Radu Nemerenco)

Webpack是一个智能工具。它的优势之一是从捆绑软件中消除垃圾代码/文件。

这意味着,如果未使用import myFile from '../myPath/myFile.jpg';或require('../ myPath / myFile.jpg');导入文件,则该文件不会成为最终捆绑包的一部分。

就您而言,您不是要导入文件。您正在创建一个字符串变量,这对webpack毫无意义。

在您的情况下,可以使用不同的选项:

选项1:预导入所有图像并将其映射到对象中:

import React, {Component} from  'react';
import image1 from '../assets/image1.png';
import image2 from '../assets/image2.png';
import image3 from '../assets/image3.png';

const imageTypes = {
  image1,
  image2,
  image3,
}

export default class MyComponent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      imageType: 'image1'
    }
  }

  render() {
    return (
      <img src={imageTypes[this.state.imageType]} />
    )
  }
}

选项2:不建议-使用require动态导入文件(可能需要Webpack配置,以便在生产包中包括所有可能的必需映像):

class MyComponent {
  constructor(props) {
    super(props);
    this.state = {
      image: 'file1.png'
    }
  }

  render() {
    return (
      <img src={require(`./assets/${this.state.image}`)} />
    )
  }
}

选项3:从API发送图片Blob(在base64中)。

我建议您根据自己的要求使用选项1选项3,例如:更改/添加/删除图像的频率。从ReactJS包中动态导入文件是不正常的,并且可能会由于来自外部源的数据而在项目中最终出现不存在的图像。

对于选项2,即使未在JS文件中的某些位置导入(硬编码)图像,也可能在配置webpack以便将所有图像都包含在包中时配置webpack时遇到一些问题。请记住,生产中的React Application最终是静态文件的集合。您需要按以下方式对待它们。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章