如何在ReactJS中实现动态图片?

8
在我的系统中,有几个图片可以供用户查看,对我来说,只需传入一个id,然后将该图像呈现给用户非常有利。
(用例之一:系统中的文章与图片相关联,有许多文章在系统中,从中提取出仅图像ID,并根据该ID动态显示图像是理想的。我没有可能为每篇文章静态地提供图像路径。)
不幸的是,我尝试了解这个问题,但一直没有进展。如果您能用“像我五岁时一样解释”来回答这个问题,我会非常感激。
我已经尝试以两种不同的方式使用图像,但很遗憾,它们都没有起作用。不幸的是,我需要两者继续使用:(
1:将其放置在div的背景中。[我在此处将其用作带有覆盖文本的轮播图。]
2:将其作为独立的图像放置。[这将占Web应用程序中95%以上的图像使用情况。]
在完美的世界中,我希望只需将此对象传递给props即可。
  articleDetails = {
        articleId: 38387,
        articleTitle: "Magical Unicorn Article"
        articleContent: "I am not that creative, but here is some content."
    }


       <IndividualArticle article={articleDetails}/>

然后,props需要将其接收并将其转换为本地文件的图像路径。
   templateStringForImage = `../../../../articleImages/${this.props.article.articleId}.png`

然后,为了将此模板字符串用作以下用途:
1:div的背景图像。
    <div
         className="container"
         style={{
             backgroundImage: `url(${templateStringForImage})`         ,                       
             height: "576px"          
    }} 
enter code here

 </div>

2:独立图片

      <Image
            src={require({templateStringForImage})}
      />

我尝试过的一些方法:

我尝试了一些更改,例如改变代码结构,使其变成:

     var Background = `../../../images/articleImages/${         
              this.props.article.image     
     }`; 

     <div style={{                
             backgroundImage: url('../../../images/articleImages/article3Image.png'),                                
              height: "576px"          
     }} 

但不幸的是,这只给了我这些错误。
 Line 32:  'url' is not defined  no-undef

当我尝试像这样使用新的背景对象时,我遇到了不同的错误。
             var Background = `../../../images/articleImages/${         
                   this.props.article.image     
            }`; 

          <Image
               src={require({Background})}
          />

错误信息如下:
         Error: Cannot find module '[object Object]'

我的当前系统/错误:

-我有一堆像article1Image.png,article2Image.png,article3Image.png这样的图片,它们在一个图像文件夹中被指定在SRC代码中。

-我想直接将“article1Image.png”传递到对象中,并生成一个图像。

-我尝试做这样的事情,但一直失败,当我试图将其用作DIV的背景图像时,甚至没有出现错误消息......它只是我的屏幕上的空白空间。没有损坏的图像图标,只是一个空白。

   var Background = `'../../../images/articleImages/${
         this.props.article.image
    }'`;

    <div
    style={{
      backgroundImage: `url(${Background})`,
      height: "576px"
    }}

- 尝试使用semantic-ui的Image时,我遇到一个非常棘手的错误。
      <Image
        src={require(Background)}
      />

错误:

 Error: Cannot find module ''../../../images/articleImages/article2Image.png''

然而令人震惊的是,当我像这样将其作为静态字符串给出时,它确实有效。
      <Image
        src={require('../../../images/articleImages/article2Image.png')}
      />

但是,即使我直接将字符串路径输入到div的backgroundImage中,它仍然显示为空...

      <div
           style={{
               backgroundImage: `url(../../../images/articleImages/article3Image.png)`,
               height: "576px"
         }}

感谢大家的帮助,我非常感激!
1个回答

18

根据您尝试的情况,有两种不同的解决方案。

URL

如果您想通过style={{ backgroundImage: 'url(...)' }}访问它们,那么URL需要从前端可访问。如果您使用了create-react-app,则意味着将图像放置在public文件夹中而不是src文件夹中。

因此,如果您在public文件夹中有图像,如:/public/articleImages/article2Image.png,则可以使用url样式属性:

const imageName = 'article2Image.png';
<div style={{ backgroundImage: `url('/articleImages/${imageName}')` }}>
  ...
</div>
<img src={`/articleImages/${imageName}`} />

如果您没有使用create-react-app配置,则需要通过您正在使用的应用程序(例如express)使图像可用。

Require

这个有点棘手,我不确定为什么它不能直接使用。
在测试时,我必须在文件顶部硬编码地要求所有的图片,然后我就可以很好地使用require(stringTemplate)。但是我遇到了一个Error: fileName hasn't been transpiled yet.,所以我不确定同样的修复方法是否适用于您。
它基本上看起来像这样:
require('../../../images/articleImages/article1Image.png');
require('../../../images/articleImages/article2Image.png');
... 
// This code would be inside a component
const imageName = 'article2Image.png';
const filePath = '../../../images/articleImages/${imageName}';
const fileUrl = require(filePath);
<div style={{ backgroundImage: `url(${fileUrl})` }}>
  ...
</div>
<img src={fileUrl} />

如果不在文件顶部加入require(s),转译就会出现问题。


我建议使用静态资源路线,这将允许您使用上面的URL技术。require更适用于不经常更改的静态文件,如图标。

如有任何问题,请随时提问,我很乐意澄清并且给出更多的例子。


非常感谢您的支持:D 到目前为止没有问题,一切都很顺利!非常感激! - J. Doe
终于读到了这个答案,对我很有帮助!谢谢你,@Matty。 - Akhila

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接