首页 > 解决方案 > 加载图像路径以使用图像 ReactJS 创建组件

问题描述

我有一个 JSON 为组件提供源道具,该组件将使用它来创建<img src={source} ... />元素。我在这里这里的stackoverflow上看到我需要使用模板文字导入图片才能使用它,<img src={require(`${source}`)} alt={title}/>其中source是一个prop,title是一个prop。

代码粘贴在下面以供参考。感谢您的耐心和帮助!

应用程序.js

  parseJson(){
   var data = require('./highlights.json');
   for (var i = 0; i < data.length; i++) {
    var obj = data[i];
    console.log("source: " + obj.src);
  }
   return data.map((obj, key) =>
    <Highlight source={obj.source} link={obj.href} title={obj.title} desc={obj.desc} key={obj.src}/>  // returns the components and passes in the appropriate props
     )
 }


  render() {
    return (
      <div className="App">
      <Menubar/>
      <div>
      <Profilepic onClick={this.toggleModal}/>
      </div>
      <div className = "HighlightsContainer">
      {this.parseJson()} // returns a bunch of components here
      </div>
      <UploadButton/>
      <UploadWindow show={this.state.uploadWindowOpen}/>

      <Modal show={this.state.isOpen}
      onClose={this.toggleModal}>
      <Signup/>
      </Modal>
      <PhotoViewer show={this.state.photoViewerOn}/>
      </div>
      );
  }

突出显示.jsx

import React from 'react';
let Highlight = function statelessFunctionComponentClass(props) {
// the 4 props that are passed in 
  let source = props.source;
  let link = props.link;
  let title = props.title;
  let desc = props.desc;

  let style = {
    position: 'relative',
    width: '300px',
    height: '300px',
    background: 'blue',
    display: 'inline-block'
  };
//returns the component of an image button
  return (
    <button style = {style}>
    <a href={link}>
//the require statement is giving issue, without it buttons are created
//without require, with it i get the error described below.
    <img src={require(`${source}`)} alt={title}/>
    </a>
    <div id="highlight1-title">{title}</div>
    <div id="highlight1-desc">{desc}</div>
    </button>
    );
};

export default Highlight;

错误 - 通过更改为 obj.src 修复了此错误 错误:找不到模块“未定义”。

  16 | return (
  17 |   <button style = {style}>
  18 |   <a href={link}>
> 19 |   <img src={require(`${source}`)} alt={title}/>
  20 |   </a>
  21 |   <div id="highlight1-title">{title}</div>
  22 |   <div id="highlight1-desc">{desc}</div>

**新模块错误**

Error: Cannot find module 'highlights/1.jpg'.
statelessFunctionComponentClass
C:/Users/auser/Documents/.../src/Component/Highlight.jsx:19

  16 | return (
  17 |   <button style = {style}>
  18 |   <a href={link}>
> 19 |   <img src={require(`${source}`)} alt={title}/>
  20 |   </a>
  21 |   <div id="highlight1-title">{title}</div>
  22 |   <div id="highlight1-desc">{desc}</div>

标签: javascriptreactjs

解决方案


我认为您的方法还有其他问题,但是您收到此错误的原因是因为这一行:

<Highlight source={obj.source} link={obj.href} title={obj.title} desc={obj.desc} key={obj.src}/>  // returns the components and passes in the appropriate props

obj.source您作为 prop 的值传入source,但从前面的代码看来,您打算将obj.src.


推荐阅读