一个允许在运行时加载字体并在 React Native 组件中使用它们的库。
expo-font
允许从网络加载字体并在 React Native 组件中使用它们。请参阅 字体 指南中更详细的使用信息。
¥expo-font
allows loading fonts from the web and using them in React Native components. See more detailed usage information in the Fonts guide.
¥Installation
-
npx expo install expo-font
If you are installing this in an existing React Native app (bare workflow), start by installing expo
in your project. Then, follow the additional instructions as mentioned by library's README under "Installation in bare React Native projects" section.
¥Configuration in app.json/app.config.js
如果你在项目中使用配置插件(EAS 构建 或 npx expo run:[android|ios]
),则可以使用其内置的 配置插件 配置 expo-font
。该插件允许你配置无法在运行时设置的各种属性,并且需要构建新的应用二进制文件才能生效。
¥You can configure expo-font
using its built-in config plugin if you use config plugins in your project (EAS Build or npx expo run:[android|ios]
). The plugin allows you to configure various properties that cannot be set at runtime and require building a new app binary to take effect.
{
"expo": {
"plugins": [
[
"expo-font",
{
"fonts": ["path/to/file.ttf"]
}
]
]
}
}
Name | Default | Description |
---|---|---|
fonts | [] | An array of font files to link to the native project. The paths should be relative to the project root, and the file names will become the font family names. |
安卓:将字体文件复制到 android/app/src/main/assets/fonts。
¥Android: Copy font files to android/app/src/main/assets/fonts.
iOS:请参阅 Apple 开发者文档中的 向你的应用添加自定义字体。
¥iOS: See Adding a Custom Font to Your App in the Apple Developer documentation.
¥Usage
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() {
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',
},
});
import * as Font from 'expo-font';
useFonts(map)
Name | Type | Description |
---|---|---|
map | string | Record<string, FontSource> | A map of |
const [loaded, error] = useFonts({ ... });
Load a map of fonts 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.
[boolean, null | Error]
boolean
) - A boolean to detect if the font for fontFamily
has finished
loading.Error | null
) - An error encountered when loading the fonts.isLoaded(fontFamily)
Name | Type | Description |
---|---|---|
fontFamily | string | The name used to load the |
Synchronously detect if the font for fontFamily
has finished loading.
boolean
Returns true
if the font has fully loaded.
isLoading(fontFamily)
Name | Type | Description |
---|---|---|
fontFamily | string | The name used to load the |
Synchronously detect if the font for fontFamily
is still being loaded.
boolean
Returns true
if the font is still loading.
loadAsync(fontFamilyOrFontMap, source)
Name | Type | Description |
---|---|---|
fontFamilyOrFontMap | string | Record<string, FontSource> | string or map of values that can be used as the |
source (optional) | FontSource | the font asset that should be loaded into the |
Highly 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.
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.
processFontFamily(fontFamily)
Name | Type | Description |
---|---|---|
fontFamily | null | string | Name of font to process. |
Used to transform font family names to the scoped name. This does not need to be called in standalone or bare apps but it will return unscoped font family names if it is called in those contexts.
string | null
Returns a name processed for use with the current workflow.
unloadAsync(fontFamilyOrFontMap, options)
Name | Type | Description |
---|---|---|
fontFamilyOrFontMap | string | Record<string, UnloadFontOptions> | The name or names of the custom fonts that will be unloaded. |
options (optional) | UnloadFontOptions | When |
Unload custom fonts matching the fontFamily
s and display values provided.
Because fonts are automatically unloaded on every platform this is mostly used for testing.
Promise<void>
FontResource
An object used to dictate the resource that is loaded into the provided font namespace when used
with loadAsync
.
Name | Type | Description |
---|---|---|
default (optional) | string | - |
display (optional) | FontDisplay | Only for: Web Sets the |
uri (optional) | string | number | - |
FontSource
Literal Type: multiple types
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
FontDisplay
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.
FontDisplay Values
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_FONT_FAMILY | 提供的字体系列名称无效。 |
错误 _ 卸载 | 尝试卸载尚未完成加载的字体。 |