Font Awesome 5个图标无法使用React(“找不到图标”错误)

时间:2018-04-30 19:51:06

标签: javascript reactjs font-awesome

我正在尝试在我的React项目中使用Font Awesome 5 Pro(我有许可证),我尽我所能遵循API中的说明,但我仍然有问题。

在我的项目中,我使用npm来安装fontawesome,fontawesome-common-types,fontawesome-pro-light,fontawesome-pro-regular,fontawesome-pro-solid和react-fontawesome。所有这些文件夹都在我的node_modules / @ fortawesome /目录

在我的App.js中,我有这些导入(这不是整个文件,只是相关的片段):

import fontawesome from '@fortawesome/fontawesome';
import FontAwesomeIcon from '@fortawesome/react-fontawesome';
import {faSpinnerThird, faCircle} from '@fortawesome/fontawesome-pro-regular/';

fontawesome.library.add(faSpinnerThird, faCircle);

然后我有另一个组件Spinner.js,代码如下:

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

const spinner = () => (
    <div className="fa-layers fa-fw">
        <FontAwesomeIcon icon="circle" color="#ddd" />
        <FontAwesomeIcon icon="spinner-third" color="#aaa" spin />
    </div>
);

export default spinner;

在另一个组件中,我正在导入Spinner组件并有条件地渲染它,但是当它被渲染时,我在浏览器控制台中出现了这些错误:

Could not find icon
Object { prefix: "fas", iconName: "circle" }

Could not find icon
Object { prefix: "fas", iconName: "spinner-third" }

我对React很陌生,但我认为我已经正确地遵循了FontAwesome的React API中的说明。知道我可能会出错吗?

3 个答案:

答案 0 :(得分:7)

我认为问题是因为默认情况下前缀是fas(Font Awesome Solid)所以在以下情况下:

<FontAwesomeIcon icon="circle" color="#ddd" />

它正在寻找fas中的circle图标,但是,您想要使用fontawesome-pro-regular中的faCircle

import {faSpinnerThird, faCircle} from '@fortawesome/fontawesome-pro-regular/';

所以我觉得你想写一些类似

的东西
<FontAwesomeIcon icon={["far", "circle"]} color="#ddd" />

另外,如果您不知道库的前缀是什么,

fontawesome.icon(faPlus).abstract

会给你一个像这样的对象:

[{
"tag": "svg",
"attributes": {
  "data-prefix": "fa",
  "data-icon": "user",
  "class": "svg-inline--fa fa-user fa-w-16",
  "role": "img",
  "xmlns": "http://www.w3.org/2000/svg",
  "viewBox": "0 0 512 512"
},
"children": [
  {
    "tag": "path",
    "attributes": {
      "fill": "currentColor",
      "d": "M96…112z"
    }
  }
]
}]

https://fontawesome.com/how-to-use/font-awesome-api

答案 1 :(得分:2)

我明白了!

默认情况下,FontAwesomeIcon组件使用“fas”前缀(对于Font Awesome Solid)。你可以在我上面发布的错误代码中看到。但是,我试图从/font-awesome-pro-regular/目录加载 Regular 权重。

我更改了FontAwesomeIcon组件以使用正确的前缀,如下所示:

<FontAwesomeIcon icon={["far", "circle"]} color="#ddd" />

现在它按预期工作。

答案 2 :(得分:0)

更改您的App.js以单独包含每个图标,我相信您可能正在解构Icon对象。

import fontawesome from '@fortawesome/fontawesome';
import FontAwesomeIcon from '@fortawesome/react-fontawesome';
import faSpinnerThird from '@fortawesome/fontawesome-pro-regular/faSpinnerThird';
import faCircle from '@fortawesome/fontawesome-pro-regular/faCircle';

fontawesome.library.add(faSpinnerThird, faCircle);

根据此处的API建议:https://www.npmjs.com/package/@fortawesome/react-fontawesome#build-a-library-to-reference-icons-throughout-your-app-more-conveniently