【发布时间】:2019-06-27 09:49:59
【问题描述】:
如何在snack.expo.io 上使用本地字体?
我有一个 ttf 字体,我想用它作为snack.expo.io 上的证据,但我不太明白我该怎么做。
一些建议?
【问题讨论】:
标签: javascript react-native fonts expo
如何在snack.expo.io 上使用本地字体?
我有一个 ttf 字体,我想用它作为snack.expo.io 上的证据,但我不太明白我该怎么做。
一些建议?
【问题讨论】:
标签: javascript react-native fonts expo
当您制作零食时,您可以导入文件。您可以看到 Project 旁边有三个垂直点,点击它会带您进入导入菜单。
选择Import files 会将您带到此屏幕,您可以在其中浏览或拖放文件。我更喜欢拖放。
然后,您可以将文件拖到您希望它们所在的文件夹中。
然后,要使用您的自定义字体,您可以按照文档中的指南进行操作。 https://docs.expo.io/versions/latest/guides/using-custom-fonts/
这是一个快速的代码示例。
import * as React from 'react';
import { Text, View, StyleSheet } from 'react-native';
import { Constants, Font } from 'expo';
// You can import from local files
export default class App extends React.Component {
// <- use the button on the left, three vertical dots to import files
// set the initial state
state = {
fontLoaded: false
}
async componentDidMount() {
// load fonts
await this.loadFonts();
}
loadFonts = async () => {
// load the font
await Font.loadAsync({
'open-sans-bold': require('./assets/fonts/OpenSans-Bold.ttf'),
});
this.setState({fontLoaded: true})
}
render() {
// use the font in your text components
// only render the Text component when the font has been loaded.
return (
<View style={styles.container}>
{this.state.fontLoaded ? (<Text style={{ fontFamily: 'open-sans-bold', fontSize: 56 }}>
Hello, world!
</Text>) : null}
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
paddingTop: Constants.statusBarHeight,
backgroundColor: '#ecf0f1',
padding: 8,
}
});
还有一份零食来证明它的工作,注意我已经将我的字体存储在文件夹./assets/fonts/https://snack.expo.io/@andypandy/custom-font
【讨论】:
state 来控制Text 组件的呈现。我已经更新了零食和代码示例以使用 Expo 建议的 state 方法。