【问题标题】:Method require() doesn't work with mapped reference image links - React方法 require() 不适用于映射的参考图像链接 - React
【发布时间】:2020-07-22 00:24:44
【问题描述】:

我有一个包含指向本地图像链接的数组的数据文件。当我尝试映射此数组并渲染图像列表时,方法 require() 允许我仅将图像文件的名称放入内部并单独访问路径,如下面代码的 image1 所示。

即使图像源看起来与 image1 示例中的相同,Image2 和 image3 也无法工作。

为什么会这样?我可以以某种方式解决它吗? 我不想在每次需要渲染图像列表时更正我的 src 属性。此外,通过导入获取图像并不是最好的方法,因为数组的长度可能很大,而且还可以动态变化。

感谢您的帮助和问候。

   // news.image = 'news-img1.jpg',
   // news.imageSrc = '../images/news-img1.jpg'

const NewsList = ({ newsList }) => {
   const listItems = newsList.map((news) => {
      return (
         <li key={news.id}>
            <img src={require(`../images/${news.image}`)} alt={news.title} /> // image1
            <img src={require(`${news.imageSrc}`)} alt={news.titleSrc} /> // image2
            <img src={require(news.imageSrc)} alt={news.titleSrc} /> // image3
         </li>
      )
   })
   return (
      <section className="news-list">
         <ul>
            {listItems}
         </ul>
      </section>
   );
}

export default NewsList;

【问题讨论】:

  • 是否可以将实际 URL 作为 imageSrc 发送?目前,如果您正在为实际的网站/应用程序这样做,这种动态导入图像的方法绝对不是理想的方法。

标签: arrays reactjs image mapping require


【解决方案1】:

如果我是你,我不会将我的图像包含在项目的 src 文件夹中,而是将它们放在 public/images 文件夹中。这样,就不需要 require 语句,因为 React 将直接复制图像,而不需要对名称或路径进行任何修改。

示例代码:

   // news.image = 'news-img1.jpg',
   // news.imageSrc = '../images/news-img1.jpg'

const NewsList = ({ newsList }) => {
   const listItems = newsList.map((news) => {
      return (
         <li key={news.id}>
            <img src={`${process.env.PUBLIC_URL}/images/${news.image}`} alt={news.title} /> // image1
         </li>
      )
   })
   return (
      <section className="news-list">
         <ul>
            {listItems}
         </ul>
      </section>
   );
}

export default NewsList;

【讨论】:

  • 但是当你不导入方法时,webpack 不会构建那些图像..
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-02
  • 2014-08-11
  • 1970-01-01
  • 1970-01-01
  • 2021-10-03
相关资源
最近更新 更多