简体   繁体   English

@ expo / vector-icons,如何使用react-navigation加载字体

[英]@expo/vector-icons, how to load font using react-navigation

I am trying to use this with react-navigation and I keep getting: 我正在尝试将其与react-navigation一起使用,并且不断得到:

fontFamily 'Feather' is not a system font and has not been loaded through Expo.Font.loadAsync fontFamily'Feather'不是系统字体,并且尚未通过Expo.Font.loadAsync加载

I am using the Font.loadAsync() method in my loading component but the error keeps showing up. 我在加载组件中使用Font.loadAsync()方法,但错误不断出现。 I actually ended up removing all vector icons from my app in order to start clean. 我实际上最终从我的应用程序中删除了所有矢量图标,以便开始清理。

So my question is if I have a switch navigator which starts with a loading screen (this starts the auth check) and switches either to login screen or root tab container which contains the meat of my app. 所以我的问题是我是否有一个以加载屏幕开头的交换机导航器(这将启动auth检查),然后切换到包含我的应用程序内容的登录屏幕或根标签容器。 I cant seem to figure out where to call Font.loadAsync() 我似乎不知道在哪里可以调用Font.loadAsync()

Here is my MainNavigator.js 这是我的MainNavigator.js

export default createBottomTabNavigator(
    {
        Friends: FriendsList,
        Profile: Profile,
        Settings: Settings
    },
    {
        defaultNavigationOptions: ({navigation}) => ({
            tabBarIcon: ({tintColor}) => {
                const {routeName} = navigation.state;
                let iconName;
                if (routeName == "Friends") {
                    iconName = "users"
                } else if (routeName == "Profile") {
                    iconName = "user"
                } else if (routeName == "Settings") {
                    iconName = "settings"
                }
                return <Feather name={iconName} size={20} color={tintColor} />
            }
        }),
        tabBarOptions: {
            style: {
                backgroundColor: "#fff"
            }, 
            inactiveTintColor: "#999",
            activeTintColor: TERTIARY_COLOR
        }
    }
)

App.js App.js

// Screens for Switch Navigator
import AuthScreens from "./components/screens/AuthScreens";
import LoadingScreen from "./components/screens/Loading";
import MainNavigator from "./MainNavigator";

const AppContainer =  createAppContainer(createSwitchNavigator(
    {
        LoadingScreen,
        AuthScreens,
        MainNavigator
    },
    {
        initialRouteName: "LoadingScreen"
    }
))

Loading Screen 载入画面

export default class LoadingScreen extends Component {
    async componentDidMount() {
        try{
            await Font.loadAsync({
                FeatherFont
            })
            firebase.auth().onAuthStateChanged(user => {
                this.props.navigation.navigate(user ? "MainContainer" : "LoginScreen")

            })
        } catch(error) {
            alert(error)
        }

    }
    render() {
        return (
            <View style={{ flex: 1, justifyContent: "center", alignItems: "center"}}>
                <ActivityIndicator/>
            </View>
        )
    }
}

You need to load them in the App.js inside _loadResourcesAsync unsing the Font.loadAsync() 您需要在App.js内部的_loadResourcesAsync加载它们,而_loadResourcesAsync打开Font.loadAsync()

_loadResourcesAsync = async () => {
   // blablabla 
    return Promise.all([
      Asset.loadAsync([
        require('random images'),
      ]),
      Font.loadAsync(
         // this line is where you load the font, name and path
        {Feather: require('./assets/fonts/Feather-path.ttf')},

      ),
    ]);
  };

And then inside the render function : 然后在render函数中:

render() {
    if (!this.state.isLoadingComplete && !this.props.skipLoadingScreen) {
      return (
        <AppLoading
          startAsync={this._loadResourcesAsync}
          onError={this._handleLoadingError}
          onFinish={this._handleFinishLoading}
        />
      );
    } else {
      return (
        <View style={styles.container}>
          <StatusBar barStyle="light-content" />
          <AppNavigator style={styles.container} />
          <BarraOffline connected={this.state.isConnected}/>
        </View>
      );
    }
  }

I don't know your definition of FeatherFont , 我不知道您对FeatherFont的定义,

but I don't think Font recognize it as a font. 但我不认为Font会将其识别为字体。

Font is the module that deals with font-related tasks. Font是处理与字体相关的任务的模块。

  1. First, we must load the font from our assets directory using Expo.Font.loadAsync() . 首先,我们必须使用Expo.Font.loadAsync()从资产目录中加载字体。
  2. We can do this in the componentDidMount() lifecycle method of the App component. 我们可以在App组件的componentDidMount()生命周期方法中执行此操作。
  3. Add the following method in App : App添加以下方法:
  4. Now that we have the font files saved to disk and the Font SDK imported, let's add this code: 现在我们已经将字体文件保存到磁盘并导入了Font SDK ,让我们添加以下代码:

We need a way to re-render the Text component when the font has finished loading. 我们需要一种在字体加载完成后重新呈现Text组件的方法。

  1. First we initialize fontLoaded to false in the App class constructor: 首先,我们在App类的构造函数中将fontLoaded初始化为false:
class App extends React.Component {
  state = {
    fontLoaded: false,
  };

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

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

With React Native you specify fonts in Text components using the fontFamily style property. 使用React Native,您可以使用fontFamily样式属性在Text组件中指定字体。 The fontFamily is the key that we used with Font.loadAsync . fontFamily是我们与Font.loadAsync使用的键。

Usage 用法

<Text style={{ fontFamily: 'open-sans-bold', fontSize: 56 }}>
  Hello, world!
</Text>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM