通过对象数组映射并为重复的 React 组件拉 imgPath

Mapping through array of objects and pulling imgPath for repeated React Component

我正在尝试展示艺术画廊的图像。我有一个 MainGallery 组件,在所述组件中是一个 Piece 组件,正在为辅助文件中的每个对象渲染 portfolio.js

Piece 组件正在为每个对象渲染,我可以访问来自对象的数据,但是即使文件路径正确,图像路径也不会显示图像。

MainGallery.js

import React, { useState } from 'react';
import portfolio from '../../portfolio';
import Piece from '../Piece/Piece';

export default function MainGallery() {
  // const [pieces, setPieces] = useState(Object.keys(portfolio).map((x) => x));

  return (
    <div>
      {Object.keys(portfolio).map((key) => (
        <Piece
          key={key}
          index={key} // if we need access to key we need to pass it down as prop as something other than 'key'
          details={portfolio[key]}
        />
      ))}
    </div>
  );
}
Piece.js

import React from 'react';

export default class Piece extends React.Component {
  render() {
    // deconstruct properties for Piece
    const { title, imgPath, description } = this.props.details;

    return (
      <div className="single-piece">
        {console.log(imgPath)}
        <h1>{title}</h1>
        <img src={imgPath} alt={title} />
        <p>{description}</p>
      </div>
    );
  }
}
portfolio.js

const portfolio = [
  {
    title: 'Storm',
    imgPath: '../../images/storm.jpg',
    description: 'An owl done with ',
    type: 'misc',
    style: 'acrylic',
  },
  {
    title: 'eagle',
    imgPath: '../../images/eagle.jpg',
    description: 'A bald eagle in the wild',
    type: 'pet',
    style: 'paint',
  },
  {
    title: 'family',
    imgPath: '../../images/family.jpg',
    description: 'A portrait of my son and nieces.',
    type: 'people',
    style: 'pastel',
  },
];

export default portfolio;

尝试在 src 路径中使用 require。

<img src={require(imgPath)} alt={title} />

如果这不起作用,请在图像文件夹中创建一个 js 文件,然后像这样导出图像:

export const poster1 = require('./storm.jpg');

第三种选择是尝试导入组件中的所有图像,但这需要对代码进行更多更改。

import storm from '../../images/storm.jpg'

最后要尝试的是确保将所有图像保存在 public 文件夹而不是 src 中。然后像这样访问它们:

<img src='/images/storm.jpg' />

希望对您有所帮助。