我试图通过单击待办事项列表项来切换 Font Awesome 图标。这是整个组件...
import React from 'react';
import './TodoItem.scss';
class TodoItem extends React.Component {
constructor(props) {
super(props);
this.state = {
complete: false
}
this.toggleComplete = this.toggleComplete.bind(this);
}
toggleComplete() {
this.setState(prevState => ({
complete: !prevState.complete
}));
}
render() {
const incompleteIcon = <span className="far fa-circle todo-item-icon"></span>;
const completeIcon = <span className="far fa-check-circle todo-item-icon"></span>;
return (
<div className="todo-item" onClick={this.toggleComplete}>
{this.state.complete ? completeIcon : incompleteIcon}
<span className="todo-item-text">{this.props.item}</span>
</div>
);
}
}
export default TodoItem;
这是我的 FA 5 CDN(直接来自网站)...
<script defer src="https://use.fontawesome.com/releases/v5.0.1/js/all.js"></script>
我拍了一些 React 开发工具和检查器的屏幕截图......
Here is the React component while incomplete (the default)
And while complete...
And the two icon elements in the inspector, I noticed the one not being used by default is commented out.
正如您所看到的,我可以在 React 工具中手动切换完整状态和组件更改,但更改不会呈现。我更改了默认状态以确保两个图标都正确加载。我制造了一个Codepen在不同的环境和这个环境中尝试一下有效,但是我使用的是 FA 4.7.0 CDN。使用 Codepen 和 FA 4.7.0,当我检查图标时,它只是一个 HTML 元素而不是 SVG。
我想让这个组件与 FA 5 一起工作,所以任何帮助将不胜感激!
font-awesome javascript 不会在 React 重新渲染触发器上重新渲染。如果您不介意不使用新的 font-awesome svg/javascript 图标,您可以使用 font-awesome 作为带有 css 的 webfont。
在你的index.html中,删除fontawesome脚本,并添加font-awesome css样式表:
<link href="https://use.fontawesome.com/releases/v5.0.2/css/all.css" rel="stylesheet">
您的代码现在应该可以工作了。
另一种可能性是使用官方的 font-awesome React 包(这有点麻烦,但它使用了新的 svg 图标)
将必要的包添加到项目中:
yarn add @fortawesome/fontawesome @fortawesome/react-fontawesome
yarn add @fortawesome/fontawesome-free-regular @fortawesome/fontawesome-free-solid
示例代码:
import fontawesome from '@fortawesome/fontawesome'
import FontAwesomeIcon from '@fortawesome/react-fontawesome'
import { faCircle as fasCircle } from '@fortawesome/fontawesome-free-solid'
import { faCircle as farCircle } from '@fortawesome/fontawesome-free-regular'
const Circle = ({ filled, onClick }) => {
return (
<div onClick={onClick} >
<FontAwesomeIcon icon={filled ? farCircle : fasCircle}/>
</div>
);
};
class App extends React.Component {
state = { filled: false };
handleClick = () => {
this.setState({ filled: !this.state.filled });
};
render() {
return <Circle filled={this.state.filled} onClick={this.handleClick} />;
}
}
有关更多信息,请参阅 github 存储库:https://github.com/FortAwesome/react-fontawesome
这个答案是我的答案的编辑版本:如何让 Font Awesome 5 与 React 一起使用?.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)