动态导入图像(React Js)(需要img路径找不到模块)

Vah*_*hid 11 javascript base-url ecmascript-6 reactjs

我需要通过地图方法从我的图像文件动态导入图像(几个)。首先,我想为图像文件设置一个基本URL,然后从包含image属性的JSON文件中读取图像的名称,然后相应地设置图像src。JSON文件如下所示:

{
      "title": "Blue Stripe Stoneware Plate",
      "brand": "Kiriko",
      "price": 40,
      "description": "Lorem ipsum dolor sit amet...",
      "image": "blue-stripe-stoneware-plate.jpg"
    },
    {
      "title": "Hand Painted Blue Flat Dish",
      "brand": "Kiriko",
      "price": 28,
      "description": "Lorem ipsum dolor sit amet...",
      "image": "hand-painted-blue-flat-dish.jpg"
    },
Run Code Online (Sandbox Code Playgroud)

我的图片文件夹: 在此处输入图片说明

我已经阅读了redux的产品,它非常适合=>

const products = this.props.products;
console.log(products, 'from redux'); 
const fetchProducts = [];
    for (let key in products) {
      fetchProducts.push({
        ...products[key]
      });
    }
Run Code Online (Sandbox Code Playgroud)

console.log()=> 在此处输入图片说明

现在,我想定义一个像这样的基本URL,稍后通过在map方法中添加JSON文件中的图像名称来用作图像src:

const baseUrl = '../../components/assets/images/';
const fetchProducts = [];
for (let key in products) {
  fetchProducts.push({
    ...products[key]
  });
}

const productCategory = fetchProducts.map((product, index) => {
  return (
    <Photo
      key={index}
      title={product.title}
      brand={product.brand}
      description={product.description}
      imageSource={baseUrl + product.image}
      imageAlt={product.title}
    />
  );
});
Run Code Online (Sandbox Code Playgroud)

我的照片组件如下所示:

  const photo = props => (
  <div className={classes.Column}>
    <img src={require( `${ props.imageSource }` )} alt={props.imageAlt} />
    <div className={classes.Container}>
      <p>{props.brand}</p>
      <p>{props.title}</p>
      <p>{props.price}</p>
    </div>
  </div>
);

export default photo;
Run Code Online (Sandbox Code Playgroud)

不幸的是,我遇到了这个错误: 在此处输入图片说明 在此先感谢您,我的英语不好:)

dev*_*kan 11

导入不是那样工作的。您可以使用这样的基本 URL:

const baseUrl = "../../components/assets/images/";
Run Code Online (Sandbox Code Playgroud)

然后你可以Photo像这样传递给你的组件:

<Photo
  key={index} // Don't use index as a key! Find some unique value.
  title={product.title}
  brand={product.brand}
  description={product.description}
  imageSource={baseUrl + product.image}
  imageAlt={pro.title}
/>;
Run Code Online (Sandbox Code Playgroud)

最后,在您的Photo组件中使用require

<img src={require( `${ props.imageSource }` )} alt={props.imageAlt} />
Run Code Online (Sandbox Code Playgroud)

或者像这样:

<img src={require( "" + props.src )} alt={props.imageAlt} />
Run Code Online (Sandbox Code Playgroud)

但是,不要跳过""部分或不要直接使用它,例如:

<img width="100" alt="foo" src={require( props.src )} />
Run Code Online (Sandbox Code Playgroud)

因为require想要一个绝对路径字符串,前两个做这个技巧。