React.js无法呈现正确的字体真棒图标

时间:2018-04-27 11:15:38

标签: javascript html css reactjs font-awesome

我在使用font-awesome图标的react.js中遇到问题。在这里,我想使用条件运算符渲染不同的图标。我能够正确地看到span标签渲染的值,但不能看到字体真棒图标。

我能够看到图标在这里呈现为svg。但我不确定是什么导致了这个问题。

感谢任何帮助。

图标链接为solid https://fontawesome.com/icons/star?style=solid

图标链接常规:https://fontawesome.com/icons/star?style=regular

jsFiddle:https://jsfiddle.net/69z2wepo/182809/

class Hello extends React.Component {
  constructor(props){
    super(props);
    this.state = {
       toggle: true
    }
  }
  toggle(){
    this.setState({toggle: !this.state.toggle});
  }
  render() {
    return (
    <div>
      Hello {this.props.name}
      {
        this.state.toggle ? (
        <span><i className="fas fa-star"></i>solid</span>
        ) : (
        <span><i className="far fa-star default-preference"></i>regular</span>
        )
      }
      <div>
        <button onClick={this.toggle.bind(this)}> Toggle </button>
      </div>
    </div>
    )
  }
}

ReactDOM.render(
  <Hello name="World" />,
  document.getElementById('container')
);

3 个答案:

答案 0 :(得分:3)

字体真棒的javascript并没有在React rerender触发器上重新渲染。如果你没有使用新的字体 - 真棒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反应包

向项目添加必要的包:

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 repo:https://github.com/FortAwesome/react-fontawesome

答案 1 :(得分:1)

我添加了这个(从https://fontawesome.com/get-started获取)并且工作正常

<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.0.10/css/all.css" integrity="sha384-+d0P83n9kaQMCwj8F4RJB66tzIwOKmrdb46+porD/OvrJ+37WqIM7UoBtwHO6Nlg" crossorigin="anonymous">

并删除了fontawesome js文件

答案 2 :(得分:0)

您还可以使用 React Icons https://gorangajic.github.io/react-icons/

  

当前支持的图标反映图标

Material Design Icons by Google https://www.google.com/design/icons/ (licence: CC-BY 4.0)
Font Awesome by Dave Gandy - http://fontawesome.io (licence: SIL OFL 1.1)
Typicons by Stephen Hutchings - http://typicons.com (licence: CC BY-SA)
Github Octicons icons by Github https://octicons.github.com/ (licence: SIL OFL 1.1)

等。