【问题标题】:Mapping through array of objects and pulling imgPath for repeated React Component通过对象数组映射并为重复的 React 组件拉取 imgPath
【发布时间】:2021-04-16 00:30:57
【问题描述】:

我正在尝试为艺术画廊展示图片。我有一个 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;

【问题讨论】:

    标签: javascript reactjs image components mapping


    【解决方案1】:

    尝试在 src 路径中使用 require。

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

    如果不行,在 images 文件夹中创建一个 js 文件并像这样导出图像:

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

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

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

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

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

    希望对您有所帮助。

    【讨论】:

    • 将图像文件夹移动到公用文件夹而不是 src 成功了!
    猜你喜欢
    • 2021-05-19
    • 2019-11-21
    • 2023-04-08
    • 1970-01-01
    • 2023-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多