繁体   English   中英

使用 ReactJS 动态加载本地图像

[英]Dynamically Loading Local Images with ReactJS

我正在尝试从数组中渲染多个图像,并将其作为属性传递到“图像”组件上。 但是,无论出于何种原因,我想要渲染的本地图像都没有显示出来。 如果我加载托管在某个网址的图像,则会显示该图像,表明将“imageSource”属性传递给 Image 组件没有任何问题。 我试过像这样使用源格式:

let source = 'require(./img/' + props.imageSource + ")";

或尝试:

<img src={{uri: source}} role="presentation" style={style.image} />

......但我所做的一切都没有任何区别。

该组件如下所示。 我完全被困住了,所以非常感谢帮助!

import React from 'react';

let Image = function statelessFunctionComponentClass(props) {

  let source = './img/' + props.imageSource;

  const style = {

    image : {

      width: '400pt',
      height: '400pt'
    }
  }

  return (

    <img src={source} role="presentation" style={style.image} />
  )
}

export default Image

您可以通过使用 require.context() 创建一个新上下文来包含图像文件夹。 从那里,您可以从该文件夹动态访问所需的图像,并将其设置为 src。

离开这样的结构:

APP
├──webpack.config.js
├──src
     ├──containers
        ├──YourContainer.js
     ├──components
        ├──YourComponent.js
├──public
     ├──bundle.js
     ├──images
           ├──dog.png
           ├──cat.png

在 YourContainer.js 中,您想创建一个新的上下文来要求该图像目录

const images = require.context('../../public/images', true);

从那里,您可以专门引用图像:

const dog = images('./dog.png');

或动态:

let animal = images(`./${someVariable}.png`);

一个更完整的例子,这里是你如何在迭代对象时执行它,使用键来拉你的图像,并将它作为样式道具传递给子组件:

let YourContainer = ({ dispatch }) => {
const data = projectData["projectData"];

// Require context image folder
const images = require.context('../../public/images', true);


return (        
    <div className="container-fluid">
        <Row>
            {
                // Iterate over data object
                Object.keys(data).map((keyname, keyindex)=> {

                    let code = data[keyname]["code"];
                    let title = data[keyname]["title"];
                    // Dynamically reference image
                    // Set as inline style
                    // Pass as prop to child
                    let imgsrc = images(`./${code}.png`);

                    let styler = {
                        backgroundImage: `url(${imgsrc})`
                    }

                    return <YourComponent 
                                key={keyindex}
                                title={title} 
                                style={styler} 
                            />
                })
            }   
        </Row>      
    </div>  
)   
}

看到这个问题还没有人回答,我也太在找答案了,

我遇到了一个使用 url 加载图像的绝妙技巧

假设您正在使用 create-react-app 插件

您可以使用公共文件夹动态渲染图像

例如,如果您在 React 应用程序的公共文件夹中放置了一个名为“image.jpg”的图像。

您可以通过执行以下操作来加载它

<img src={`${process.env.PUBLIC_URL}/image.jpg`} />

可以在下面找到更多信息。 https://create-react-app.dev/docs/using-the-public-folder

提及您拥有图像的图像文件夹路径。 我在“SRC”文件夹下创建了文件夹。 所以我保持我的代码如下。

let images = require.context('../../../assets/images', true);

let itemImg = images(`./${dynamicObject.photo}`).default;

默认是主要关键字。

问题

您遇到的问题是使用文件系统上的相对路径和操作类似但略有不同的 URL 路径混合使用本地“要求”样式。

例如:

require('./some-resource.x')

告诉构建系统在相对于当前文件的本地目录中查找文件。 重要的一点是它是使用它的构建系统。

当您使用 React 组件或浏览器中任何正在运行的 javascript 时,没有本地磁盘的概念,只有运行它的页面/窗口上下文。

执行以下操作实际上是无效的:

require('/img/some_image.jpg')

也不

<img src="./img/some_image.jpg" />

因为第一个指的是文件系统的根,这不太可能是您想要的,第二个指的是浏览器并不真正支持的概念(免责声明:他们可能会使用它,我还没有测试过) .

我认为您的img目录可能与创建包的位置无关。

你该怎么办?

如果您遵循public文件夹的通常结构,那么可能是images (或在您的情况下是img ),那么网络服务器将根据其配置为公共目录提供服务,这可能是http://server/publichttp://server/static甚至直接在根地址 ( http://server/ ) 下。

在 DOM 的上下文中,也就是上面提到的页面/窗口上下文,只有在当前位置引用图像才有意义,所以http://server/path/to/page/img/image.jpg ,或根位置。 无论哪种方式,您都应该执行以下操作:

import React from 'react';

const Image = function statelessFunctionComponentClass(props) {

  let source = props.imageIsRelative ?
                 'img/' + props.imageSource :
                 '/img/' + props.imageSource;

  const style = {
    image : {
      width: '400pt',
      height: '400pt'
    }
  }

  return (
    <img src={source} role="presentation" style={style.image} />
  )
}

export default Image

请注意,区别只是前面的/ ,它指示路径是相对于当前页面还是相对于网络服务器的根目录。

我遇到了这个问题并找到了一种解决方法,我不需要将图像放入我的公共文件夹中。 我的文件夹结构看起来像这样。

APP
├──src
     ├──components
        ├──ProjectCard.js
     ├──images
           ├──pic1.png
           ├──pic2.png

我通过一个道具通过了我的形象。 为此,我使用 MaterialUI Card 组件作为模板。

您应该使用require.context()指向您使用以下行存储图像的文件夹。 我把我的放在进口下面。

const images = require.context('../images', true);

然后,当您尝试加载图像时,您应该使用以下行来使用调用。 您可以将.png替换为.jpg或您正在使用的任何图像类型。

images(`./${prop.imageName}.png`).default;

下面是一个示例,它被来自自定义 Material UI Card 组件的更多代码包围,其中myprop.imgName是不带文件类型的图像名称。

/* imports */
const images = require.context('../images', true);  /* This is the key line 1 */

export default function MyCard({ myprop }) { {*/ Remember to include your props */}
    return (
        <Card sx={{ maxWidth: 345 }}>
            <CardMedia
                component="img"
                height="140"
                image={images(`./${myprop.imgName}.png`).default} {/*Dynamic image loaded via prop*/}
                alt={myprop.imgName}

            />
            {/* ... other code ... */}
        </Card>
    );
}

在查看 StackOverflow 之后,我最大的问题是我需要在我的images()调用结束时包含default关键字。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM