我正在尝试在react中导入整个图标文件夹。这是正确的方法。实际上我是从API获取数据所以基于该数据我希望生成一些图标,这些图标都存储在某个文件夹中。这样做的正确方法是什么?
答案 0 :(得分:0)
根据我的经验,你可以做两件事导入静态方式或动态导入
静态方式如下:
import as icons from '../icons';
// This way you have a reference of the entire folder
// and when referencing each icon I think you can accessed if like it was an object
我之前从未使用此方法(带孔文件夹),因此您可以尝试控制台日志中的图标引用,如console.log(icons);并查看返回的内容
动态的方式是这样的:
// in the function that executes which icon is going to be displayed
// based on the response returned from the api you can do this
if(randomApi === "randomResponse") {
import('./icons/icon1').then(icon => {
this.setState({ iconToDisplay: icon });
})
} else if (randomApi2 === "randomResponse2") {
import('./icons/icon2').then(icon => {
this.setState({ iconToDisplay: icon });
})
}
像这样的东西
进一步阅读:
https://webpack.js.org/guides/code-splitting/#dynamic-imports