首页 > 解决方案 > 如何在样式化组件中向主题提供程序添加自定义字体?

问题描述

我正在使用带有 TypeScript 的 material-ui styled-components 构建一个 React 应用程序。

我正在尝试在我的样式组件中使用自定义字体,但我很难让它工作。

我做的第一件事是创建了一个globalStyles.ts文件createGlobalStyle

import { createGlobalStyle } from "styled-components";

export const theme = {
  primaryBlue: "#0794B4",
  secondaryBlue: "#043157",
  primaryWhite: "#fff"
};

const GlobalStyle = createGlobalStyle`
  @font-face {
    font-family: pala;
    src: url("./assets/pala.ttf") format('truetype');
    font-weight: normal;
    font-style: normal;
  }
  html {
    font-size: 10px;
  }
`;
export default GlobalStyle;

我将ThemeProviderand添加GlobalStyle到我的应用程序中:

import React, { Component } from "react";
import "./App.css";
import NavBar from "./components/NavBar";
import { ThemeProvider } from "styled-components";
import GlobalStyle, { theme } from "./globalStyles";

class App extends Component {
  render() {
    return (
      <ThemeProvider theme={theme}>
        <div className="App-header">
          <NavBar title="MyCompany" />
          <GlobalStyle />
        </div>
      </ThemeProvider>
    );
  }
}

export default App;

然后我尝试在我的样式组件中使用这种字体:

import React, { PureComponent } from "react";
import styled from "styled-components";
import AppBar from "@material-ui/core/AppBar";
import Toolbar from "@material-ui/core/Toolbar";
import Typography from "@material-ui/core/Typography";

export const StyledAppBar = styled(AppBar)``;
export const StyledToolbar = styled(Toolbar)``;
export const StyledTypography = styled(Typography)`
  && {
    font-family: pala;
    font-size: 10rem;
    color: ${props => props.theme.primaryWhite};
  }
`;

export interface Props {
  title: string;
}

export class NavBar extends PureComponent<Props> {
  render() {
    return (
      <StyledAppBar>
        <StyledToolbar>
          <StyledTypography>{this.props.title}</StyledTypography>
        </StyledToolbar>
      </StyledAppBar>
    );
  }
}

export default NavBar;

颜色和字体大小的样式已正确应用,但自定义字体未正确应用。我是否必须以某种方式将自定义字体添加到ThemeProvider并使用它props.theme.font?还是我做错了什么?

标签: reactjstypescriptmaterial-uistyled-componentsjss

解决方案


使用 styled-components createGlobalStyle 声明自定义字体:

  1. 像导入模块一样导入字体
  2. 使用标记的模板文字将其插入到您的@font-face声明中。

这是你的globalStyles.ts

// globalStyles.ts

import { createGlobalStyle } from "styled-components";
// 1. import the font
import pala from "./assets/pala.ttf";

export const theme = {
  primaryBlue: "#0794B4",
  secondaryBlue: "#043157",
  primaryWhite: "#fff"
};

// 2. interpolate it using tagged template literals
const GlobalStyle = createGlobalStyle`
  @font-face {
    font-family: pala;
    src: url(${pala}) format('truetype');
    font-weight: normal;
    font-style: normal;
  }
  html {
    font-size: 10px;
  }
`;

export default GlobalStyle;

如果您想了解有关样式组件中标记模板文字的更多信息,Max Stoiber(创建样式组件)写了一篇关于它的非常好的文章


推荐阅读