全球样式表中的世博字体

问题描述:

我正在使用世博会,并且需要在全局样式表中使用自定义字体。世博documents这一点,但它是不是在我的情况下,相关的,因为componentDidMount()只在一个类中执行:全球样式表中的世博字体

class App extends React.Component { 
    componentDidMount() { 
    Font.loadAsync({ 
     'open-sans-bold': require('./assets/fonts/OpenSans-Bold.ttf'), 
    }); 
    } 

    // ... 
} 

我的全域样式看起来是这样的:

const React = require('react-native'); 

import { 
    Dimensions, 
    StatusBar, 
} from 'react-native'; 

const { StyleSheet } = React; 

export default { 
    // ... 
} 

我结束了在短短加载字体导航文件,然后可以在我的全局样式表和整个应用程序中访问这些字体。

世博会中的字体加载是“懒惰”的,因为您可以在加载之前创建引用字体的StyleSheet对象。例如,下面的代码是有效的:

async function exampleAsync() { 
    let stylesheet = StyleSheet.create({ 
    fancyText: { 
     ...Expo.Font.style('open-sans-bold'), 
    }, 
    }); 

    await Expo.Font.loadAsync({ 
    'open-sans-bold': require('./assets/fonts/OpenSans-Bold.ttf'), 
    }); 
} 

所以你不需要调用内componentDidMountExpo.Font.loadAsync必然,它是确定加载字体之前调用StyleSheet.createExpo.Font.style

重要的是,在渲染其样式使用加载字体的组件之前,您需要等待Expo.Font.loadAsync才能完成。

你可以做的只是在你的root/top组件中添加一个状态标志来检查字体异步是否已经完成。

然后在渲染方法中添加一个条件,以确保只有在字体被成功载入后,您的子组件才会被渲染。请参阅示例

 export default class App extends React.Component { 
     state = { 
     fontLoaded: false, 
     } 

     componentDidMount() { 
     this.loadAssetsAsync(); 
     } 

     async loadAssetsAsync() { 
     await Expo.Font.loadAsync({ 
     'open-sans-bold': require('./assets/fonts/OpenSans-Bold.ttf'), 
     });; 

     this.setState({ fontLoaded: true }); 
     } 

     render() { 
     if (!this.state.fontLoaded) { 
      return <AppLoading />; // render some progress indicator 
     } 

     return (
      <Navigator /> //render your child components tree 
     ); 
     } 
    }