React Webpack动态文件名

时间:2018-08-01 17:48:29

标签: javascript reactjs webpack eslint

我有100个图像资产,分别代表用户可能处于的级别(级别1-100)。现在,我以内联样式显示这样的图标:

const backgroundImg = require(`app/images/levels/${currentLevel}.svg`);

return (
  <div
    style={{ backgroundImage: `url(${backgroundImg})` }}
  />
);

根据用户级别,要求这些图像的更好方法是什么? (当前会引发导入/无动态需求错误)

1 个答案:

答案 0 :(得分:3)

const getImagePerLevel = (currentLevel) => {
    return import(`app/images/levels/${currentLevel}.svg`);
}

return (
  <div
    style={{ backgroundImage: `url(${getImagePerLevel(currentLevel)})` }}
  />
);