首页 文章

哪个导入用于FontAwesomeIcon,React和Jest?

提问于
浏览
1

我有一个React站点(使用TypeScript和Webpack),它使用FortAwesome的 react-fontawesome 包来渲染图标 . 此包导入如下:

import FontAwesomeIcon from '@fortawesome/react-fontawesome';

在使用Enzyme添加Jest测试时,任何使用包含对 FontAwesomeIcon 的引用的组件的测试都会失败,并显示以下内容:

Warning: React.createElement: type is invalid -- expected a string (for built-in
components) or a class/function (for composite components) but got: undefined. 
You likely forgot to export your component from the file it's defined in, or you might
have mixed up default and named imports.

将这些组件的导入更改为:

import * as FontAwesomeIcon from '@fortawesome/react-fontawesome';

修复测试,但随后浏览到包含该组件的页面失败:

Warning: React.createElement: type is invalid -- expected a string (for built-in
components) or a class/function (for composite components) but got: object.

我预计这是ES6,Babel和月亮阶段之间的冲突,但经过几个小时的战斗后,我已经没有想法......

2 回答

  • 0

    正如预期的那样,这是标准的冲突,与TypeScript的关系比其他任何事情都要多 . 解决方案是将 "allowSyntheticDefaultImports": true 添加到 tsconfig.json 文件中 . 希望这有助于那些追求...

  • 1

    如果你想使用
    import * as FontAwesomeIcon from '@fortawesome/react-fontawesome';
    那么你必须使用:
    <FontAwesomeIcon.default icon={faUser} />
    (=你拿起函数/ react-component)

    import * 将非对象转换为对象,并添加指向原始模块类型的 .default 属性(在我们的示例中为函数) . 您导入/用于创建新反应组件的每个组件都应该是函数,类或标记字符串(例如 <div> ),而不是对象,这就是您收到 type is invalid 错误的原因 . React.createElement() docs

    检查这个sandbox以查看带有 import * as 的fontawesome的工作示例 .
    请注意在沙箱控制台上记录的"imports"之间的区别

    我使用create-react-app在本地测试了你的情况,没有任何问题可以开玩笑或做出反应 .

    编辑:你得到的两个错误都与反应有关(不是打字稿或开玩笑) .

相关问题