react-native - React Native 仅加载一次自定义字体

标签 react-native fonts

我只想加载自定义字体一次(可能在应用程序加载期间)并在应用程序内的任何位置使用它。目前,我正在使用 async-await 方法在每个使用它的页面上加载字体。这可以在 native react 中完成吗? 谢谢。

最佳答案

您在使用世博会吗?在这种情况下,在 App.js(或应用程序的第一个文件加载)中应该很容易

您可以看到下面的示例:

import { Font } from 'expo'

class App extends Component {
  constructor(props) {
    super(props)
    this.state = {
      fontLoaded: false
    }
  }

  async componentDidMount() {
    try {
      await Font.loadAsync({
        MyFontName: require('./path/my-font.otf'),
        MyFontName2: require('./path/my-font-2.otf')
      })
      this.setState({ fontLoaded: true })
    } catch (error) {
      console.log(error)
      return
    }
  }

  render() {
    const { fontLoaded } = this.state

    if (fontLoaded) {
      return (
        <View>
          <Text>Fonts are loaded !</Text>
        </View>
      )
    }

    return (
      <View>
        <Text>Loading fonts ...</Text>
      </View>
    )
  }
}

export default App

之后,您可以在应用的所有样式中使用该字体的名称。

MyCustomStyle: {
  fontFamily: 'MyFontName'
}

希望可以帮到你

关于react-native - React Native 仅加载一次自定义字体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57652148/

相关文章:

.net - 小型大写字母字体属性?

javascript - 使用 python 或 javascript 将 Hershey 字体 .jhf 解析为 json

react-native - 一个 React Native 屏幕可以包含在两个不同的堆栈导航器中吗?

react-native - 如何在 react 原生 redux 中显示和隐藏事件指示符?

javascript - 下载到Android手机时如何保护受版权保护的多媒体文件?

amazon-web-services - 为什么我的用户会收到此与 AWS 相关的错误?

javascript - 选择模板时出现 Expo 错误 : Could not get npm url for package

Java:OTF字体的使用,检查特定字体是否存在

iphone - 是否有 Safari Mobile(即 iPad 和 iPhone)支持的字体列表?

javascript - 如何在 HTML Canvas 中使用不同颜色的文本