如何在样式化组件中向主题提供者添加自定义字体?

时间:2018-11-01 14:32:42

标签: reactjs typescript material-ui styled-components jss

我正在使用Material-ui样式化的组件和TypeScript构建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;

我将ThemeProviderGlobalStyle添加到了我的应用中:

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使用它?还是我做错了什么?

1 个答案:

答案 0 :(得分:1)

要声明具有样式组件的自定义字体createGlobalStyle:

  1. 导入字体,就像导入模块一样
  2. 使用tagged template literals将其插入您的@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(创建样式化组件的作者)会写a really nice article about it