动态图像导入

时间:2020-01-28 10:06:11

标签: javascript reactjs

因此,我有一个组件,需要使用具有超过28个选项的特定图像,所以我编写了2个函数,它们看起来像这样,以动态导入图像:

    loadAvatar = imageName => {
        // Imports Avatar image file and returns it
        import(`../../../img/avatars/${imageName}.svg`).then(image => {
            return image;
        });
    };

    getAvatarIcon(icon, color) {
        // Uses Avatar icon and color defined in endpoint response to return proper file name
        var avatarFileName = "Avatar_" + icon + "_" + color;
        return this.loadAvatar(avatarFileName);
    }

然后我尝试使用此名称

<img src={() => this.getAvatarIcon(icon, color)} alt={name} className="avatar" />

但是,这不起作用,我该如何解决?

2 个答案:

答案 0 :(得分:1)

尝试一下:

<img src={this.getAvatarIcon(icon, color)} alt={name} className="avatar" />

将您的loadAvatar函数编辑为:

loadAvatar = imageName => import(`../../../img/avatars/${imageName}.svg`);

并将getAvatarIcon修改为:

async getAvatarIcon(icon, color) {
    // Uses Avatar icon and color defined in endpoint response to return proper file name
    var avatarFileName = "Avatar_" + icon + "_" + color;
    return await this.loadAvatar(avatarFileName);
}

答案 1 :(得分:1)

好的,所以我做了几件事:

  • 切换到require()而不是import()来直接获取图像,而不是获取包含它作为参数的对象。
  • 运行ComponentDidMount()函数而不是render()方法,以防止无限循环。
  • 将图像保存为状态,并在我的render()中使用它,而不是返回函数值。

这是我的最终代码的样子

    // When Mount
    componentDidMount() {
        this.getAvatarIcon(this.props.icon, this.props.color);
    }

    async getAvatarIcon(icon, color) {
        // Uses Avatar icon and color defined in endpoint response to return proper file name
        var avatarFileName = "Avatar_" + icon + "_" + color;
        return await this.loadAvatar(avatarFileName);
    }

    async loadAvatar(imageName) {
        // Imports Avatar image file and sets it in the component state
        const avatar = await require(`../../../img/avatars/${imageName}.svg`);
        this.setState({ avatar });
    }

和在我的渲染中 <img src={avatar} alt={name} className="avatar" />