将本地字体添加到样式组件中

问题描述 投票:0回答:1

我在src目录中创建了“字体”文件夹,并将MyFont.otf放在其中,但是,我不能在样式化组件(在本例中为StyledComponent.js)中使用它。我的意思是看不到该字体。

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './components/App';
import './index.css';

ReactDOM.render(<App />, document.getElementById('root'));

index.css

@font-face {
  font-family: 'MyFont';
  src: local('MyFont'), url(./fonts/MyFont.otf) format('opentype');
}

StyledComponent

import styled from 'styled-components';

export const StyledComponent = styled.div`
  margin: 0 auto;

  h1 {
    font-family: 'MyFont'
  }
`;
css reactjs styled-components
1个回答
0
投票

[如果使用的是CRA,则可以将外部字体URL添加到public / index.html文件,例如,也可以将其添加到全局样式。

如果您使用的是样式组件<4,则可以使用:

import { injectGlobal } from "styled-components";
injectGlobal`
  @import url('https://fonts.googleapis.com/css?family=Notable');
  body {
    font-family: 'Notable', sans-serif;
  }
`

并且如果您使用的是4或更高,则可以使用:

import { createGlobalStyle } from "styled-components";
const GlobalStyles = createGlobalStyle`
  @import url('https://fonts.googleapis.com/css?family=Notable');
  body {
    font-family: 'Notable', sans-serif;
  }
`
const App = () => (
  <div>
    <GlobalStyles />
    App Content Here
  </div>
)

从[link处的频谱聊天中获取。

© www.soinside.com 2019 - 2024. All rights reserved.