模板文字&字符串插值作为javascript方法

时间:2016-11-29 21:51:27

标签: javascript reactjs ecmascript-6 string-interpolation template-literals

所以我目前有一个weatherAPI,它会返回一个字符串的图标代码,并以数字02d01d01n04d等开头。现在,我想要做的是根据图标代码动态地引入react svg组件。让我解释一下我是如何尝试的,然后你可以看看是否有更好的方法来处理这个问题。

为简单起见,我将API的响应传递给dumb component。然后我创建了一个文件夹weatherIcons,其中包含我的所有svg组件:

src
|_components
  |_dashboard
  | |_DumbComponent.js
  |_weatherIcons
    |_02d.js
    |_01d.js
    |_01n.js
    |_index.js

在我的DumbComponent.js我需要通过位于weatherIcons文件夹下的索引文件中的所有svg组件,如下所示:import * as Icon from '../common/svg/weatherIcons';

index.js文件夹中的weatherIcons文件将提供每个组件,如:

export {default as 01d} from './01d';
export {default as 02d} from './02d';
export {default as 01n} from './01n';

这样我就可以将这些文件称为DumbComponent.js内的方法,如:Icon.01d()。然后,这将返回src/components/weatherIcons/01d.js'. As you know though, this WON'T actually return that file, because a method cannot start with an integer and thus my dilemma. Nor can I give a name of 01d , 02d , 01n like I did in my weatherIcons / index.js`文件中的svg组件。

我的思维过程是给他们一个以字符开头的名字空间:

export {default as code01d} from './01d';
export {default as code02d} from './02d';
export {default as code01n} from './01n';

然后尝试从api响应中插入代码作为函数。 Icon.code${apiRESPONSE}()。关于如何做到这一点或任何其他解决当前情况的任何想法。

PS。我已经研究过react-svg和其他svg导入器,而不喜欢将svg作为html和路径导入的方法。

0 个答案:

没有答案
相关问题