gpt4 book ai didi

reactjs - 如何将自定义字体添加到样式组件中的主题提供者?

转载 作者:搜寻专家 更新时间:2023-10-30 21:34:54 25 4
gpt4 key购买 nike

我正在使用带有 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;

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

最佳答案

使用 styled-components 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 .

关于reactjs - 如何将自定义字体添加到样式组件中的主题提供者?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53103398/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com