如何为我的自定义库组件正确加载字体系列?

Rod*_*ima 1 javascript uicomponents reactjs styled-components

styled-components我正在使用和编写一个新的 React UI 组件库styled-system。该库将在业余项目中使用,并应作为 npm 库发布。

我正在创建一个按钮组件,并考虑几乎每个组件都应该有font-family Roboto这样的:

const BaseButton = styled.div`
  font-family: 'Roboto', sans-serif;
`;
Run Code Online (Sandbox Code Playgroud)

考虑到每个组件都是相互独立的,那么font-family为我的整个组件库设置一次默认值的最佳位置在哪里?

谢谢

Mar*_*ark 5

如果您希望所有组件都使用 Roboto,您应该全局设置@font-face。

import { createGlobalStyle } from "styled-components";
import Roboto from './Roboto.otf';
import SecondaryFont from './SecondaryFont.otf';

const GlobalStyles = createGlobalStyle`
  @font-face {
    font-family: 'Roboto';
    src: url('${Roboto}') format('opentype');
  }
  @font-face {
    font-family: 'SecondaryFont';
    src: url('${SecondaryFont}') format('opentype');
  }

  body {
    font-family: 'Roboto', sans-serif;
  }
`

const YourCustomProvider = ({ children }) => (
  <>
    <GlobalStyles />
    {children}
  </>
)

// Inform users to wrap their app with your provider
const App = () => {
  return (
    <YourCustomProvider>
      // Their app
    </YourCustomProvider>
  )
}
Run Code Online (Sandbox Code Playgroud)

然后在特定组件上使用辅助字体。

const RandomComponent = styled.div`
  font-family: "SecondaryFont"
`
Run Code Online (Sandbox Code Playgroud)