Reactjs visual studio react图像路径无法到达

Reactjs visual studio react图像路径无法到达,reactjs,visual-studio,visual-studio-2017,Reactjs,Visual Studio,Visual Studio 2017,所以我有一个用react.js创建的VisualStudio项目 我正在尝试动态链接到图像,但失败了。这是我正在尝试的代码: 在顶部im为路径的第一部分设置变量: this.LogoPath = '../images/' 然后我从api调用中动态地获取图像的名称 this.setState({ imageNamePath: this.state.location.imageName }) 然后我把它们浓缩起来: {`${this.LogoPath}${this.state.locatio

所以我有一个用react.js创建的VisualStudio项目

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

在顶部im为路径的第一部分设置变量:

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'

因此,它似乎在起作用,但事实并非如此。我没有收到任何错误,并且我已经破坏了图像。我的最佳猜测是react正在将图像更改为以下内容:

image-name-here.6a131799.png

当然以前有人遇到过这个问题,但我的谷歌搜索没有什么帮助


那么如何让图像显示出来呢?

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

这意味着如果文件不是使用
import myFile from'../myPath/myFile.jpg'导入的或要求('../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]} />
    )
  }
}
import React,{Component}来自'React';
从“../assets/image1.png”导入image1;
从“../assets/image2.png”导入image2;
从“../assets/image3.png”导入image3;
常量图像类型={
图1,
图2,
图3,
}
导出默认类MyComponent扩展组件{
建造师(道具){
超级(道具);
此.state={
imageType:'image1'
}
}
render(){
返回(
)
}
}
选项2:不建议使用require动态导入文件(可能需要网页包配置,以便在生产包中包含所有可能需要的图像):

类MyComponent{
建造师(道具){
超级(道具);
此.state={
图片:“file1.png”
}
}
render(){
返回(
)
}
}
选项3:从API发送图像blob(在base64中)

我建议您根据您的要求使用选项1选项3,例如:更改/添加/删除图像的频率。从ReactJS bundle动态导入文件是不正常的,您可能最终在项目中拥有一个不存在的映像,该映像由来自外部源的数据请求


对于选项2,您在配置网页包时可能会遇到一些问题,以便将可能需要渲染的所有图像包含在捆绑包中,即使这些图像未导入(硬编码)JS文件中的某个位置。请记住,生产中的React应用程序最终是静态文件的集合。您需要按如下方式对待它们。

所有好东西,谢谢。但是,由于在渲染中通过api调用数组进行im映射,因此每个图像可能会根据各自的id而有所不同。所以我需要做一个if语句来找出哪个。我想这是另一个问题。
class MyComponent {
  constructor(props) {
    super(props);
    this.state = {
      image: 'file1.png'
    }
  }

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