面试题答案
一键面试- 文件放置位置:
- 通常将自定义字体文件放在
public
目录下,比如创建一个fonts
子目录,将字体文件(如.woff
、.woff2
、.ttf
等格式)放置其中。例如,public/fonts/custom - font.woff2
。
- 通常将自定义字体文件放在
- 在页面中引入的方式:
- 在
pages/_app.js
文件中引入字体。首先,在文件顶部导入css
样式:
import '../styles/globals.css'; function MyApp({ Component, pageProps }) { return <Component {...pageProps} />; } export default MyApp;
- 然后在
styles/globals.css
中使用@font - face
规则引入字体,示例如下:
@font - face { font - family: 'CustomFont'; src: url('/fonts/custom - font.woff2') format('woff2'), url('/fonts/custom - font.woff') format('woff'); font - display: swap; }
- 之后就可以在全局样式或组件样式中使用该字体,如:
body { font - family: 'CustomFont', sans - serif; }
- 在
- 处理跨页面复用的问题:
- 通过在
_app.js
和全局样式文件(如globals.css
)中设置字体,所有页面都会继承这些样式,从而实现跨页面复用。 - 如果某些页面有特殊需求,可以在该页面的样式文件中覆盖全局字体设置,但仍然基于
@font - face
引入的字体进行操作。例如,某个页面想改变字体的粗细:
/* page - specific.css */ body { font - family: 'CustomFont', sans - serif; font - weight: 700; }
- 也可以将字体相关样式封装成一个CSS模块或Sass/LESS混合宏,以便在不同组件和页面中更方便地复用和管理。例如,使用CSS模块:
/* font.module.css */
- 通过在
.customFont { font - family: 'CustomFont', sans - serif; }
- 在组件中使用:
```jsx
import React from'react';
import fontStyles from './font.module.css';
const MyComponent = () => {
return <div className={fontStyles.customFont}>This text uses the custom font</div>;
};
export default MyComponent;