Expo 字体 iconExpo 字体

一个允许在运行时加载字体并在 React Native 组件中使用它们的库。

Android
iOS
tvOS
Web
Included in Expo Go
Bundled version:
~14.0.11

expo-font 允许从网络加载字体并在 React Native 组件中使用它们。有关更详细的使用信息,请参阅 Fonts 指南。

安装

🌐 Installation

Terminal
npx expo install expo-font

If you are installing this in an existing React Native app, make sure to install expo in your project.

应用配置中的配置

🌐 Configuration in app config

有两种方法可以向你的应用添加字体:使用 expo-font 配置插件(推荐用于 Android 和 iOS)或在运行时加载字体(适用于包括网页在内的所有平台)。

🌐 There are two ways to add fonts to your app: using the expo-font config plugin (recommended for Android and iOS) or loading them at runtime (which works across all platforms including web).

在 Android 和 iOS 上,该插件允许你在构建时嵌入字体文件,这比 useFontsloadAsync 更高效。设置好配置插件并运行 prebuild 后,你可以立即渲染自定义字体。该插件可以通过不同方式进行配置,具体用法请参阅 Fonts 指南。

🌐 On Android and iOS, the plugin allows you to embed font files at build time which is more efficient than useFonts or loadAsync. After you set up the config plugin and run prebuild, you can render custom fonts right away. The plugin can be configured in different ways, see the Fonts guide on how to use it.

Example app.json with config plugin

app.json
{ "expo": { "plugins": [ [ "expo-font", { "fonts": ["./path/to/file.ttf"], "android": { "fonts": [ { "fontFamily": "Source Serif 4", "fontDefinitions": [ { "path": "./path/to/SourceSerif4-ExtraBold.ttf", "weight": 800 } ] } ] } } ] ] } }

Configurable properties

NameDefaultDescription
fonts[]

一个字体定义数组,用于链接到本地项目。路径应相对于项目根目录。在 Android 上,文件名将作为字体族名称。在 iOS 上,字体族名称始终直接取自字体文件,可能与文件名不同——请遵循 命名建议 或使用 getLoadedFonts 查看可用字体。

android[]

一个在 Android 上链接到本地项目的字体定义数组。使用对象语法可以嵌入带自定义字体族名称的 XML 字体

ios[]

一个在 iOS 上链接到本地项目的字体文件路径数组。字体族名称直接取自字体文件。

Are you using this library in an existing React Native app?

用法

🌐 Usage

如果你不想使用 config 插件,你可以在运行时通过 useFonts 钩子加载字体,如下面的代码片段所示:

🌐 If you don't want to use the config plugin, you can load a font at runtime with the useFonts hook, as shown in the snippet:

Example of loading and using a custom font
import { useFonts } from 'expo-font'; import * as SplashScreen from 'expo-splash-screen'; import { useEffect } from 'react'; import { Text, View, StyleSheet } from 'react-native'; SplashScreen.preventAutoHideAsync(); export default function App() { // Use `useFonts` only if you can't use the config plugin. const [loaded, error] = useFonts({ 'Inter-Black': require('./assets/fonts/Inter-Black.otf'), }); useEffect(() => { if (loaded || error) { SplashScreen.hideAsync(); } }, [loaded, error]); if (!loaded && !error) { return null; } return ( <View style={styles.container}> <Text style={{ fontFamily: 'Inter-Black', fontSize: 30 }}>Inter Black</Text> <Text style={{ fontSize: 30 }}>Platform Default</Text> </View> ); } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', }, });

应用接口

🌐 API

import * as Font from 'expo-font';

Hooks

useFonts(map)

Android
iOS
tvOS
Web
ParameterTypeDescription
mapstring | Record<string, FontSource>

A map of fontFamilys to FontSources. After loading the font you can use the key in the fontFamily style prop of a Text element.


Load a map of fonts at runtime with loadAsync. This returns a boolean if the fonts are loaded and ready to use. It also returns an error if something went wrong, to use in development.

Note, the fonts are not "reloaded" when you dynamically change the font map.

Returns:
[boolean, null | Error]
  • loaded (boolean) - A boolean to detect if the font for fontFamily has finished loading.
  • error (Error | null) - An error encountered when loading the fonts.

Example

const [loaded, error] = useFonts({ 'Inter-Black': require('./assets/fonts/Inter-Black.otf'), });

Methods

getLoadedFonts()

Android
iOS
tvOS
Web

Synchronously get all the fonts that have been loaded. This includes fonts that were bundled at build time using the config plugin, as well as those loaded at runtime using loadAsync.

Returns:
string[]

Returns array of strings which you can use as fontFamily style prop.

isLoaded(fontFamily)

Android
iOS
tvOS
Web
ParameterTypeDescription
fontFamilystring

The name used to load the FontResource.


Synchronously detect if the font for fontFamily has finished loading.

Returns:
boolean

Returns true if the font has fully loaded.

isLoading(fontFamily)

Android
iOS
tvOS
Web
ParameterTypeDescription
fontFamilystring

The name used to load the FontResource.


Synchronously detect if the font for fontFamily is still being loaded.

Returns:
boolean

Returns true if the font is still loading.

loadAsync(fontFamilyOrFontMap, source)

Android
iOS
tvOS
Web
ParameterTypeDescription
fontFamilyOrFontMapstring | Record<string, FontSource>

String or map of values that can be used as the fontFamily style prop with React Native Text elements.

source(optional)FontSource

The font asset that should be loaded into the fontFamily namespace.


An efficient method for loading fonts from static or remote resources which can then be used with the platform's native text elements. In the browser, this generates a @font-face block in a shared style sheet for fonts. No CSS is needed to use this method.

Note: We recommend using the config plugin instead whenever possible.

Returns:
Promise<void>

Returns a promise that fulfils when the font has loaded. Often you may want to wrap the method in a try/catch/finally to ensure the app continues if the font fails to load.

renderToImageAsync(glyphs, options)

Android
iOS
ParameterTypeDescription
glyphsstring

Text to be exported.

options(optional)RenderToImageOptions

RenderToImageOptions.


Creates an image with provided text.

Returns:
Promise<string>

Promise which fulfils with uri to image.

Interfaces

RenderToImageOptions

Android
iOS
tvOS
Web
PropertyTypeDescription
color(optional)string

Font color

Default:'black'
fontFamily(optional)string

Font family name.

Default:system default
size(optional)number

Size of the font.

Default:24

Types

FontResource

Android
iOS
tvOS
Web

An object used to dictate the resource that is loaded into the provided font namespace when used with loadAsync.

PropertyTypeDescription
default(optional)string
-
display(optional)FontDisplay
Only for:
Web

Sets the font-display property for a given typeface in the browser.

uri(optional)string | number
-

FontSource

Android
iOS
tvOS
Web

Literal Type: union

The different types of assets you can provide to the loadAsync() function. A font source can be a URI, a module ID, or an Expo Asset.

Acceptable values are: string | number | Asset | FontResource

Enums

FontDisplay

Web

Sets the font-display for a given typeface. The default font value on web is FontDisplay.AUTO. Even though setting the fontDisplay does nothing on native platforms, the default behavior emulates FontDisplay.SWAP on flagship devices like iOS, Samsung, Pixel, etc. Default functionality varies on One Plus devices. In the browser this value is set in the generated @font-face CSS block and not as a style property meaning you cannot dynamically change this value based on the element it's used in.

AUTO

FontDisplay.AUTO = "auto"

(Default) The font display strategy is defined by the user agent or platform. This generally defaults to the text being invisible until the font is loaded. Good for buttons or banners that require a specific treatment.

BLOCK

FontDisplay.BLOCK = "block"

The text will be invisible until the font has loaded. If the font fails to load then nothing will appear - it's best to turn this off when debugging missing text.

FALLBACK

FontDisplay.FALLBACK = "fallback"

Splits the behavior between SWAP and BLOCK. There will be a 100ms timeout where the text with a custom font is invisible, after that the text will either swap to the styled text or it'll show the unstyled text and continue to load the custom font. This is good for buttons that need a custom font but should also be quickly available to screen-readers.

OPTIONAL

FontDisplay.OPTIONAL = "optional"

This works almost identically to FALLBACK, the only difference is that the browser will decide to load the font based on slow connection speed or critical resource demand.

SWAP

FontDisplay.SWAP = "swap"

Fallback text is rendered immediately with a default font while the desired font is loaded. This is good for making the content appear to load instantly and is usually preferred.

错误代码

🌐 Error codes

代码描述
ERR_FONT_API如果传递给 loadAsync 的参数无效。
ERR_FONT_SOURCE提供的资源类型不正确。
ERR_WEB_ENVIRONMENT浏览器的 document 元素不支持注入字体。
ERR_DOWNLOAD下载提供的资源失败。
ERR_FONT_FAMILY提供的字体族名称无效。
ERR_UNLOAD尝试卸载尚未加载完成的字体。