gpt4 book ai didi

javascript - 尝试从 react 中的函数获取值时出错

转载 作者:行者123 更新时间:2023-11-28 17:26:57 26 4
gpt4 key购买 nike

我有一个 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

但我不断收到此错误:

Uncaught TypeError: Object(...) is not a function

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中有没有办法做到这一点?

谢谢!

最佳答案

documentIconsnamed 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]

关于javascript - 尝试从 react 中的函数获取值时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51331836/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com