首页 > 解决方案 > 如何在 ReactJS 中做动态图像?

问题描述

在我的系统中,我有一些用户可以呈现的图像,并且能够只传递一个 id 然后将该图像呈现给用户,这对我来说非常有利。

(一个用例:系统中的文章有与之关联的图像,系统中有很多文章,最好只提取 image-id 并根据该 id 动态显示图像。没有现实可能的方式我可以静态地为每篇文章提供一个图像路径。)

不幸的是,我试图弄清楚这一点,但并没有走得太远。我会非常感谢“像我 5 岁一样向我解释”这个答案。

我一直在尝试以两种不同的方式使用图像,但不幸的是,这两种方式都对我不起作用不幸的是,我需要两者都继续:(

1:把它作为一个div的背景。[我在这里将其用作带有重叠文本的轮播。]

2:把它当作一个独立的图像。[这将弥补通过 webapp 使用图像的 95% 以上的情况。]

我很想在一个完美的世界中将这样的对象传递给道具。

  articleDetails = {
        articleId: 38387,
        articleTitle: "Magical Unicorn Article"
        articleContent: "I am not that creative, but here is some content."
    }


       <IndividualArticle article={articleDetails}/>

然后让道具将其接收并将其转换为我本地文件的图像路径。

   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     
     }`; 

​</p>

     <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]'

我当前的系统/错误:

-我在图像文件夹中的 src 代码中指定了一堆图像,如 article1Image.png、article2Image.png、article3Image.png。

-我想直接将“article1Image.png”传递给对象并生成图像。

- 我试图做这样的事情,但它一直失败,不幸的是,当我尝试将它用作 div 上的 backgroundImage 时,我什至没有收到错误消息......它实际上只是我屏幕上的空白区域。没有损坏的图像图标,只是一个空白。

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

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

-当尝试使用语义用户界面的图像时,我也遇到了一个令人讨厌的错误

      <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"
         }}

谢谢大家,我真的很感激很多很多的帮助!

标签: reactjsimagejsxsemantic-ui-react

解决方案


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

网址

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

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

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

如果您没有使用 create-react-app 配置,那么您将需要通过您正在为您的应用程序提供服务的方式(即express)使图像可用。

要求

这个有点棘手,我不是 100% 为什么它不能开箱即用。

测试时我必须做的是要求文件顶部的所有图像,硬编码,然后我就可以使用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更适合像图标一样不经常更改的静态文件。

随时提出任何问题,我很乐意澄清并提供更多示例。


推荐阅读