Next JS 中的 Font Awesome 6(测试版)和动态图标名称

问题描述 投票:0回答:3

我正在用 Next JS 开发一个网站。这是我第一次使用这种语言,我还有很多东西要学。

现在,我订阅了 Font Awesome 专业版,我希望按照他们的指南中的描述,直接在我的项目中使用他们的组件。

https://fontawesome.com/v6.0/docs/web/use-with/react/

https://fontawesome.com/v6.0/docs/web/use-with/react/add-icons

基本上,只需使用这样的组件:

<FontAwesomeIcon icon={brands("google")} />

有效。

我无法解决的问题是如何在先前初始化的变量中动态设置“google”值。我需要它,因为这些值是动态地来自数据库的。

如果我尝试:

var example = "google";
<FontAwesomeIcon icon={brands(example)} />

然后我收到此错误:“引用图标时仅支持字符串文字(此处改用字符串)”。

有人有什么想法吗?

next.js font-awesome
3个回答
10
投票

导入图标的方式使用了 babel 宏。这意味着在构建时必须知道引用的图标。它只是行不通,因为 Babel 无法确定应该导入什么图标,只能在运行时完成。这就是为什么它告诉你只支持字符串文字。

所以你需要使用 second 方法,在文档中解释。您必须在图标和数据库中的值之间建立某种映射,然后获取相关图标。像这样的东西:

// not sure about exact import
import { faGoogle } from '@fortawesome/free-brand-svg-icons';

// you'd put all valid values that can come from the backend here
const myIcons = {
  google: faGoogle
}

// ...

const example = 'google';
<FontAwesomeIcon icon={myIcons[example]} />

另一个选项是使用

library.add
explained here 然后执行与上面相同的操作,但不要使用导入的图标,而是使用字符串,例如
google: 'fa-brands fa-google'
(再次,不确定这里的确切值)。


0
投票

以下是否可行?

var example = ['fab', 'google'];

<FontAwesomeIcon icon={example} />

附言建议在 ES6 中使用

let
const
关键字。


0
投票

// 工具

const UpperFirst = (sentence) => {
    if (!sentence || (typeof sentence !== 'string')) return null
    return `${sentence.charAt(0).toUpperCase()}${sentence.slice(1)}`
}

// React 通用组件

import React from 'react'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import * as solid from '@fortawesome/free-solid-svg-icons'
import * as regular from '@fortawesome/free-regular-svg-icons'
import { UpperFirst } from '@utils'

const GenFontAwe = ({ isReg, customClass, nameIco }) => {
    if (!nameIco) return null
    const finalName = nameIco.split('-').map((cv, ind) => ind === 0 ? cv : UpperFirst(cv)).join('')
    const finalIcon = isReg ? regular[finalName] : solid[finalName]
    if(!finalIcon) return null
    return <FontAwesomeIcon icon={finalIcon} className={customClass || ''} />
}

export default GenFontAwe

// 那样消费:

<GenFontAwe nameIco='fa-folder-open' isReg customClass="h1 p-5" />
© www.soinside.com 2019 - 2024. All rights reserved.