我正在尝试向我的 React 应用程序添加一个图标,该图标可以有条件地是 plus 或 minus。该图标包含在一个圆形按钮内,除了未显示其应包含的图标之外,该按钮可以正常工作。
这是我的代码:
const [isOpen, setIsOpen] = useState(false)
const handleOpening = () => {
setIsOpen((prev) => !prev)
}
<button onClick = {handleOpening} className = 'expandButton'>
{!isOpen ? (
<FontAwesomeIcon icon="fa-solid fa-plus" />
) : (
<FontAwesomeIcon icon="fa-solid fa-minus" />-</div>
)}
</button>
这是我的 package.json 文件及其包含的依赖项:
"dependencies": {
"@fortawesome/fontawesome-svg-core": "^6.5.2",
"@fortawesome/free-brands-svg-icons": "^6.5.2",
"@fortawesome/free-regular-svg-icons": "^6.5.2",
"@fortawesome/free-solid-svg-icons": "^6.5.2",
"@fortawesome/react-fontawesome": "^0.2.0",
我用这个命令安装的:
npm i --save @fortawesome/fontawesome-svg-core
npm i --save @fortawesome/free-solid-svg-icons
npm i --save @fortawesome/free-regular-svg-icons
npm i --save @fortawesome/free-brands-svg-icons
npm i --save @fortawesome/react-fontawesome@latest
我相信你忘记全局导入图标了。
尝试如下导入:
import { library } from '@fortawesome/fontawesome-svg-core';
import { fab } from '@fortawesome/free-brands-svg-icons';
import { fas } from '@fortawesome/free-solid-svg-icons';
import { far } from '@fortawesome/free-regular-svg-icons';
export default App;
library.add(fas); // Import fa-solid icons only
// library.add(fab, fas, far); // Import multiple fa styles icons
否则,需要单独导入图标:
import { faPlus, faMinus } from '@fortawesome/free-solid-svg-icons';
<button onClick={handleOpening} className="expandButton">
{!isOpen ? (
<FontAwesomeIcon icon={faPlus} />
) : (
<FontAwesomeIcon icon={faMinus} />
)}
</button>