我有一个react组件,我从另一个文件导入一个函数,如下所示:
import documentIcons from '/documentIcons';然后我试着像这样使用这个函数:
let file = this.state.selectedFile; //this returns fine
let fileExt = file.name.split('.').pop(); //this also works
let fileIcon = documentIcons(fileExt); //this throws the error但是我一直收到这个错误:
未捕获对象:TypeError(...)不是函数
documentIcons.js文件如下所示:
const icons= {
"jlr": "/icn/typeA.png",
"trr": "/icn/typeB.png",
"bpx": "/icn/typeC.png",
};
export const documentIcons = (f) => {
this.icons.find(f)
}我传入了一个文件扩展名(jlr、trr或bpx),并希望返回该图标的路径。
在react/es6中有没有办法做到这一点?
谢谢!
发布于 2018-07-14 03:41:03
documentIcons为named export,应为imported as one
import { documentIcons } from '/documentIcons'另一个选项是将命名导出更改为default export
const documentIcons = (f) => {
this.icons.find(f) // this error is handled below
}
export default documentIcons您还应该从方法中删除this,因为icons是作用域中的常量,而不是同一对象上的属性。对象没有find方法,您应该使用括号表示法来获取值,然后返回它:
const documentIcons = (f) => icons[f]发布于 2018-07-14 03:49:46
这里有几个缺失的部分。
首先,使用default导出您的函数,或者将其作为命名函数导入:
import { documentIcons } from "/documentIcons";第二,你不能在一个对象上使用.map。如果你想找到带有对象键的url,就像这样使用它:
icons[f]第三,您的函数没有返回任何内容。像这样使用它:
export const documentIcons = (f) => icons.[f];这是以下内容的简写:
export const documentIcons = (f) => {
return icons.[f]
}https://stackoverflow.com/questions/51331836
复制相似问题