reactjs - 如何在React组件渲染中使用font-face字体系列?

标签 reactjs

索引.css

  @font-face{
    font-family:"Bauhaus";
    src:local('BAUHS'),
      url('./BAUHS.ttf') format('truetype');
  }

我想根据特定条件在我的react组件index.js文件中使用“Bauhaus”字体。请您帮忙看看如何使用它。

这是我的代码:

 import './index.css';
 class NameForm extends React.Component {
   constructor(props) {
      super(props);
      this.state = {fontFamilyName: ''};

      this.handleChange = this.handleChange.bind(this);
   }
    handleChange(event) { 
     this.setState({fontFamilyName: event.target.value});
    } 
    render() { 
      return ( 
            <div> 
                <select onChange={this.handleChange}>
                   <option value='Arial'>Arial</option>
                   <option value='Bauhaus'>Bauhaus</option>
                   <option value='Times New Roman'>Times New Roman</option> 
                </select> 
                <p style={{fontFamily:this.state.fontFamilyName}}>Some Text here</p>
            </div> ); 
     }
   }

最佳答案

请记住,“truetype”适用于 Safari、Android 和 iOS ( https://css-tricks.com/snippets/css/using-font-face/ )。

以这种方式声明字体(只是我的一个项目中的一个示例):

@font-face {
font-family: '3dumbregular';
src: url('fonts/3Dumb-webfont.eot');
src: url('fonts/3Dumb-webfont.eot?#iefix') format('embedded-opentype'),
     url('fonts/3Dumb-webfont.woff') format('woff'),
     url('fonts/3Dumb-webfont.ttf') format('truetype'),
     url('fonts/3Dumb-webfont.svg#3dumbregular') format('svg');
}

支持多种浏览器的多种格式。

在您的示例中,您甚至错过了“select”值。添加值以选择:

<select onChange={this.handleChange} value = {this.state.fontFamilyName}>
           <option value='Arial'>Arial</option>
           <option value='Bauhaus'>Bauhaus</option>
           <option value='Times New Roman'>Times New Roman</option> 
 </select>

关于reactjs - 如何在React组件渲染中使用font-face字体系列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50965945/

相关文章:

reactjs - Ramda 或者不是 Ramda

javascript - 如何在React Native中调用带有来自另一个类的参数的函数?

javascript - PropTypes 给我一个字符串类型错误

reactjs - map 组件: Cannot read property 'initialize' of undefined

javascript - Mui v5.0.4 makeStyles, withStyles 不会对 mui 组件应用样式

reactjs - 如何使用 Apollo 从 GraphQL Mutation 设置身份验证 token cookie

javascript - 在 webpack 中使用加载器如何影响您的构建文件?

javascript - Material UI 自定义主题颜色分配 Typescript

rest - 让 React + Backbone 应用程序在没有集合的情况下保持安静

reactjs - Microsoft Office-ui-fabric-react 与 Fluent-ui-react - 选择哪个?