在React组件中动态导入图像 [英] Import image dynamically in React component

查看:48
本文介绍了在React组件中动态导入图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Articles组件,其中显示了一个列出了文章的博客页面.

I have an Articles component that shows a blog page with listed articles.

render() {
    const articles = {
        ...this.state.articles
    }

    const article = Object.keys(articles).map(cur => {
        return <Article
            key={this.state.articles[cur].id}
            imgName={this.state.articles[cur].thumb}
            title={this.state.articles[cur].title}
            meta={this.state.articles[cur].meta}
            clicked={() => this.detailedHandler(this.state.articles[cur].id)}
            detailed={this.state.articles[cur].detailed} />
    });

如您所见,我将带有道具的图像名称传递给Article组件.然后,我想为每篇文章显示适当的图像.

As you can see I pass image name with props to Article component. I want then to display the appropriate image for each article.

如何基于我从文章"组件中收到的道具(props.imgName)导入文章"组件中的图像?

How do I import an image in Article component based on the props I receive (props.imgName) from Articles component?

推荐答案

我使用了上下文.

const images = require.context('../../../assets/img', true);
loadImage = imageName => (assets(`./${imageName}`).default);
<img src={loadImage("someimage.png")} alt="" />

我不知道这是否是最佳解决方案,但是它可以工作.

I don't know if this is an optimal solution, but it works.

这篇关于在React组件中动态导入图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆