如何让Font Awesome 5与React一起使用? [英] How can I get Font Awesome 5 to work with React?
问题描述
在以下示例中,初始图标呈现但在类更改时不会更改。
In the following example, the initial icon renders but it does not change when the class changes.
const Circle = ({ filled, onClick }) => {
const className = filled ? 'fas fa-circle' : 'far fa-circle';
return (
<div onClick={onClick} >
<i className={className} />
<p>(class is {className})</p>
</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} />;
}
}
ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://use.fontawesome.com/releases/v5.0.2/js/all.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
推荐答案
BO41是对的,它是字体真棒的javascript不回复。如果你没有使用新的字体 - 真棒svg / javascript图标,你可以使用font-awesome作为带css的webfont。
BO41 is right, it is the font-awesome javascript that doesn't rerender. If you are okay with not using the new font-awesome svg/javascript icons, you can use font-awesome as a webfont with css.
在你的index.html中,删除fontawesome脚本,并添加font-awesome css样式表:
In your index.html, delete the fontawesome script, and add the font-awesome css stylesheet:
<link href="https://use.fontawesome.com/releases/v5.0.2/css/all.css" rel="stylesheet">
您的代码现在可以使用。
Your code should work now.
另一种可能性是使用官方字体 - 真棒反应包(这有点麻烦,但它使用新的svg图标)
The other possibility is to use the official font-awesome react package (it's a bit more of a hassle, but it uses the new svg icons)
为项目添加必要的包:
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
See the github repo for more information: https://github.com/FortAwesome/react-fontawesome
这篇关于如何让Font Awesome 5与React一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!