React - 使用道具加载动态图像
React - Dynamic Image loading using props
我正在尝试使用存储在 this.props.src
中的图像 src 加载图像。 this.props.src
输出我要加载的 img 文件的正确名称:"koolImg"。我通过以下方式导入文件:import koolImg from '../img/koolImg.png'.
这是当前设置:<img src={this.props.src} alt="noLoad"/>
。但是,没有加载图像,只显示 "alt" 值。我错过了什么?我是 React 新手。
我使用 npx create-react-app koolImgApp
命令创建了这个 React 应用程序,因此使用了 webpack。 运行 在 React 16.4.1 上使用 Google Chrome 67.
koolImg
只是一个字符串,不能直接用作 img
元素的 src
属性。
您可以通过将导入的图像变量存储在一个对象中,然后使用您的 src
属性字符串访问它来将其映射到您导入的图像:
例子
import React, { Component } from 'react';
import koolImg from '../img/koolImg.png';
const images = {
koolImg
};
class ImgSrc extends Component {
render() {
return <img src={images[this.props.src]} />;
}
}
我正在尝试使用存储在 this.props.src
中的图像 src 加载图像。 this.props.src
输出我要加载的 img 文件的正确名称:"koolImg"。我通过以下方式导入文件:import koolImg from '../img/koolImg.png'.
这是当前设置:<img src={this.props.src} alt="noLoad"/>
。但是,没有加载图像,只显示 "alt" 值。我错过了什么?我是 React 新手。
我使用 npx create-react-app koolImgApp
命令创建了这个 React 应用程序,因此使用了 webpack。 运行 在 React 16.4.1 上使用 Google Chrome 67.
koolImg
只是一个字符串,不能直接用作 img
元素的 src
属性。
您可以通过将导入的图像变量存储在一个对象中,然后使用您的 src
属性字符串访问它来将其映射到您导入的图像:
例子
import React, { Component } from 'react';
import koolImg from '../img/koolImg.png';
const images = {
koolImg
};
class ImgSrc extends Component {
render() {
return <img src={images[this.props.src]} />;
}
}