reactjs React.js:如何发送Fontawsome图标作为 prop ?

f0brbegy  于 2022-12-29  发布在  React
关注(0)|答案(3)|浏览(145)

我使用此对象作为React.js组件 prop 。但发送后,FontAwsome无法找到传递的图标

{
      key: 'editButton',
      title: 'Edit',
      icon: 'faEdit',
      function: null,
      type: 'default ',
    },
    {
      key: 'deleteButton',
      title: 'Delete',
      icon: 'faTrash',
      type: 'danger',
      function: null,
    },

我的组件:

<FontAwesomeIcon icon={item.icon} />

错误:

index.js:1 Could not find icon {prefix: "fas", iconName: "faEdit"}
piok6c0g

piok6c0g1#

如果你需要把它作为一个字符串值传递,那么你需要先预注册它们:https://fontawesome.com/how-to-use/javascript-api/methods/library-add
另请参阅:Import all icons from Fontawesome
否则,您可以显式传递它们:

import { faEdit } from '@fortawesome/free-solid-svg-icons';

...
 {
     key: 'editButton',
     title: 'Edit',
     icon: faEdit,
     function: null,
     type: 'default ',
 },
xn1cxnb4

xn1cxnb42#

我通过一个简单的条件解决了这个问题。使用

<componentName theIcon="faCrown" />

在呈现componentName时,我使用了

<FontAwesomeIcon icon={props.theIcon=== "faCrown" ? faCrown: faLink} />

您还需要导入这些图标

6yjfywim

6yjfywim3#

    • 下面是我如何在自定义输入中传递一个图标作为prop**
// custom Input with Tailwind Css and formik
import { FaUser } from 'react-icons/fa';

// inside Input component  

<label 
     htmlFor={name} 
     className='block 
     text-sm font-medium 
     text-gray-900 
     dark:text-white'>
 Full Name
</label>

<div className='relative'>
   {icon && (
            <div className='flex 
                   absolute inset-y-0 
                   left-0 pl-3 items-center 
                   pointer-events-none'>
               {icon} // <== displaying the passed icon into Input
            </div>
  )}
  <input type='text' {...field} {...props} /> //<-- formik
</div>

// You call it where you want it as follow
<Input 
      type='text'
      name='name'
      label='Full Name'
      // Passing icon below as prop
      icon={<FaUser className={iconCls} fill='currentColor' />} 
/>
    • 结果**

相关问题