因此,我有一个组件,需要使用具有超过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" />
但是,这不起作用,我该如何解决?
答案 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)
好的,所以我做了几件事:
这是我的最终代码的样子
// 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" />