reactjs ChakraUI自定义字体不会覆盖默认字体

sxissh06  于 2023-06-22  发布在  React
关注(0)|答案(1)|浏览(71)

我遵循了ChakraUI提供的设置自托管字体here的指南。当我创建TextHeading组件时,显示的字体是ChakraUI的默认字体设置。我知道自定义主题文件工作正常,因为我可以使用我设置的自定义颜色(brand.tm)。我还知道字体包是导入的,因为在ChakraUI HeadingText组件上,如果我显式地将fontFamily prop设置为“Open Sans”、“Raleway”或“Roboto”,它们就可以工作了。如果我还保留了prop并注解掉字体包导入,它就会停止工作,所以我可以确认字体包正在导入。
我采取的步骤:

  • 我使用npm install @fontsource/open-sans @fontsource/raleway安装了软件包
  • 已将字体包导入theme.ts
  • headingbody属性设置为字体系列
  • 将导出的theme添加到ChakraProvider

一些细节:

  • React应用
  • 使用Vite构建
  • 没有CSS框架(tailwindcss、bootstrap等)

我看到过一些例子,人们只是用一个“字体 Package 器”来 Package 他们的应用程序,但是有没有一种方法可以用ChakraProvider和自定义主题配置来实现呢?

theme.ts

import '@fontsource/roboto';
import '@fontsource/raleway/400.css';
import '@fontsource/open-sans/700.css';
import { ThemeConfig, extendTheme } from '@chakra-ui/react';

const config: ThemeConfig = {
    initialColorMode: 'dark',
    useSystemColorMode: true,
};

const fonts = {
    heading: `'Open Sans', sans-serif`,
    body: `Raleway, sans-serif`,
};

const colors = {
    brand: {
        tm: 'tomato',
        tl: 'teal',
    },
};

const theme = extendTheme({
    config,
    fonts,
    colors,
});

export default theme;
main.tsx

import React from 'react';
import ReactDOM from 'react-dom/client';
import theme from './theme';
import App from './App.tsx';
import { ToastContainer } from './utils/toastHandler.ts';
import { ChakraProvider, ColorModeScript } from '@chakra-ui/react';
import { BrowserRouter } from 'react-router-dom';

ReactDOM.createRoot(document.getElementById('root') as HTMLElement).render(
    <React.StrictMode>
        <ChakraProvider theme={theme}>
            <BrowserRouter>
                <App />
                <ColorModeScript initialColorMode={theme.config.initialColorMode} />
                <ToastContainer />
            </BrowserRouter>
        </ChakraProvider>
    </React.StrictMode>
);
Dependencies

  "dependencies": {
    "@chakra-ui/react": "^2.7.0",
    "@emotion/react": "^11.11.0",
    "@emotion/styled": "^11.11.0",
    "@fontsource/open-sans": "^5.0.2",
    "@fontsource/raleway": "^5.0.2",
    "@fontsource/roboto": "^5.0.2",
    "framer-motion": "^10.12.16",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-icons": "^4.9.0",
    "react-router-dom": "^6.11.2"
  },
  "devDependencies": {
    "@types/react": "^18.0.28",
    "@types/react-dom": "^18.0.11",
    "@typescript-eslint/eslint-plugin": "^5.57.1",
    "@typescript-eslint/parser": "^5.57.1",
    "@vitejs/plugin-react": "^4.0.0",
    "eslint": "^8.38.0",
    "eslint-plugin-react-hooks": "^4.6.0",
    "eslint-plugin-react-refresh": "^0.3.4",
    "typescript": "^5.0.2",
    "vite": "^4.3.2"
  }
j2cgzkjk

j2cgzkjk1#

import '@fontsource/roboto';
import '@fontsource/raleway/400.css';
import '@fontsource/open-sans/700.css';

put these in main.tsx

相关问题