reactjs - 如何在样式化组件中向主题提供程序添加自定义字体?
问题描述
我正在使用带有 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;
我将ThemeProvider
and添加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
?还是我做错了什么?
解决方案
使用 styled-components createGlobalStyle 声明自定义字体:
- 像导入模块一样导入字体
- 使用标记的模板文字将其插入到您的
@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(创建样式组件)写了一篇关于它的非常好的文章。
推荐阅读
- javascript - 寻找素数。如何提高我的代码效率
- javascript - 如何在Javascript中推送数组中的循环值
- graphql - NestJs/Graphql:“CustomObject”在解析器中定义,但不在模式中
- google-cloud-platform - Google Cloud Tasks 未随机执行任务
- html - 使用 CSS 以特定的数字顺序排列布局
- c++ - C++ 填充多维 std::arrays
- c# - C# 从 MySQL 下载空 Blob
- javascript - 用js处理文件无需下载
- r - 如何在RMD中将一个表格行分成多行
- c - 在 C 中表示二叉树的递归函数