reactjs 导入图标动态React字体

wz8daaqr  于 2022-12-26  发布在  React
关注(0)|答案(5)|浏览(134)

我在react js项目中使用FontawesomeIcon,图标名称来自数据库,我想从@fortawesome/free-solid-svg-icons动态导入来自数据库的图标

import React, { Component } from "react";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import {faImage} from "@fortawesome/free-solid-svg-icons";

export class Features extends Component {
  render() {
    return (
      <div id="features" className="text-center">
        <div className="container-fluid">
          <div className="features-listing">
            {this.props.data.map((item, index) => (
              <div key={`${index}`}>
                {" "}
                <FontAwesomeIcon icon={item.icon} />
                <h3>{item.title}</h3>
              </div>
            ))}
          </div>
        </div>
      </div>
    );
  }
}

export default Features;
mlnl4t2r

mlnl4t2r1#

在App.js中,您可以导入所有图标,如this post中所示,如下所示:

import {library} from '@fortawesome/fontawesome-svg-core';
import * as Icons from '@fortawesome/free-solid-svg-icons';

const iconList = Object.keys(Icons)
  .filter((key) => key !== 'fas' && key !== 'prefix')
  .map((icon) => Icons[icon]);

library.add(...iconList);

然后,在组件内部,仅导入FontAwesomeIcon并使用它们:

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

<FontAwesomeIcon icon="times" />
jfgube3f

jfgube3f2#

其实有一个更好的方法,不用迭代所有图标(@Andrei Rosu的解决方案),可以导出整个brandsolid包:

import { library } from '@fortawesome/fontawesome-svg-core'
import { fab } from '@fortawesome/free-brands-svg-icons'
import { fas } from '@fortawesome/free-solid-svg-icons'

// This exports the whole icon packs for Brand and Solid.
library.add(fab, fas)

并使用它们:

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

<FontAwesomeIcon icon={['fab', 'apple']} /> // any icon from Brand.
<FontAwesomeIcon icon={['fas', 'coffee']} /> // any icon from Solid.
vkc1a9a2

vkc1a9a23#

这可以是做没有输入所有的图标使用react的动态输入.仅仅替换这输入字符串与任何动态变量你需要.

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

function example(){
  const Icon = React.lazy(() => import('@fortawesome/free-solid-svg-icons/faEnvelope').then(({definition}) => ({default: () => <FontAwesomeIcon icon={definition} />})));
    
  return <React.Suspense><Icon /></React.Suspense>;
}
qf9go6mv

qf9go6mv4#

我不认为有任何必要导入所有图标。您可以在app.js中导入一些图标,如:

import {library} from '@fortawesome/fontawesome-svg-core';
import { faAngleRight, faArrowRight ... } from '@fortawesome/pro-light-svg-icons'; 

library.add(faAngleRight, faArrowRight, ...)

然后像这样使用它:

<FontAwesomeIcon icon="fal fa-angle-right" />

或者作为 prop 动态用于任何组件(如带图标的按钮):

<FontAwesomeIcon icon={icon} />
c0vxltue

c0vxltue5#

只需将Fontawesome CDN添加到您的HTML Header并使用您想要的任何图标,
在react中,它将是这样:

<i className={object.ico}><i/>

Object.ico应该是包含图标名称的字符串,如far fa-xyz

相关问题