FontAwesomeIcon“已定义但从未使用过”,即使它是必需的

时间:2018-10-02 16:06:40

标签: reactjs font-awesome

我最近将FontAwesomeReact添加到了我的React网站。我正在使用显示在每个页面上的补充工具栏组件中的图标。

页面:

import React from 'react'
import Header from '../components/header'
import Sidebar from '../components/sidebar'
import Layout from '../components/layout'
import Footer from '../components/footer'

class IndexPage extends React.Component {
    render() {
        return (
            <Header />
            <Sidebar />
            <Layout>
                <p>Hello there is some content here </p>
            </Layout>
            <Footer />
        )
    }
}

侧边栏组件:

import React from 'react'
import Menucard from '../components/menucard'
import { library } from '@fortawesome/fontawesome-svg-core'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { faInfoCircle, /*...*/, faCheck} from '@fortawesome/free-solid-svg-icons'
library.add(faInfoCircle,/*...*/,faCheck)

const clubAdminMenu = (
  <div>
    <h2>Club Admin</h2>
    <ul>
      <li className="pod">
        <a href="..."><FontAwesomeIcon icon="user" pull="right" /> Manage Registrations</a>
      </li>
      <li className="pod">
        <a href="..."><FontAwesomeIcon ... /> ...<a>
      </li>
      ...
    </ul>
  </div>
)


class Sidebar extends React.Component {
render() {
    return (
      <div className="Sidebar">
        <Menucard content={clubAdminMenu} />
        ...
      </div>
    )
  }
}

export default Sidebar
  • 起初,我假设<FontAwesomeIcon />会在所有地方定义,因为它是在<Sidebar />中导入的,并且<Sidebar />在每一页上。显然我错了,除非我在每个页面上明确包含import { FontAwesomeIcon } from '@fortawesome/react-fontawesome',否则图标就不会显示在任何页面上。
  • 但是,当我在每页上都包含import时,编译器会警告我'FontAwesomeIcon' is defined but never used大约成千上万次(在每个正文中不包含<FontAwesomeIcon />的页面上,即使它包含在<Sidebar />中,我也知道为什么要这样说,但是如果删除导入,图标将不会显示在该页面的侧栏中。

这两件事似乎相互矛盾。我想念什么吗?有更好的方法吗?

2 个答案:

答案 0 :(得分:0)

导入时

 import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'

您需要致电

  <FontAwesomeIcon />

收到该消息的原因是因为您只是导入它而从未调用过它。照我上面建议的去做

答案 1 :(得分:0)

这是 Font Awesome v5.15 的官方文档 https://fontawesome.com/v5.15/how-to-use/on-the-web/using-with/react

它说你需要在 App.js 中包含下面的代码(不一定,但如果你想在很多文件中使用字体真棒图标,这是一个好主意它是全球性的)

import { library } from "@fortawesome/fontawesome-svg-core";
import { fab } from "@fortawesome/free-brands-svg-icons";   // To use branded icons such as Google, Github, etc.
import {
    faCheckSquare,
    faCoffee,
    faInfoCircle,
    // All other icons (except fab) that you want to use MUST be declared here 
} from "@fortawesome/free-solid-svg-icons";

library.add(fab, faCheckSquare, faCoffee, faInfoCircle);    // All icons imported must be added to the library

然后在每个文件使用Font Awesome图标,您必须包含

import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";

然后要使用 Font Awesome 图标,您需要执行以下操作:

<FontAwesomeIcon icon={[iconType, icon]} />

其中 iconType = 'fab'、'fas' 等

and icon = 'github', 'coffee' 等

<FontAwesomeIcon icon={['fab', 'google']} />
<FontAwesomeIcon icon={['fas', 'coffee']} />