【问题标题】:@expo/vector-icons, how to load font using react-navigation@expo/vector-icons,如何使用 react-navigation 加载字体
【发布时间】:2019-07-11 03:31:51
【问题描述】:

我正在尝试将它与 react-navigation 一起使用,但我不断得到:

fontFamily 'Feather' 不是系统字体,尚未加载 通过 Expo.Font.loadAsync

我在加载组件中使用了 Font.loadAsync() 方法,但错误不断出现。实际上,我最终从我的应用程序中删除了所有矢量图标以开始清理。

所以我的问题是我是否有一个切换导航器,它以加载屏幕开始(这会启动身份验证检查)并切换到登录屏幕或包含我的应用程序内容的根选项卡容器。我似乎无法弄清楚在哪里调用 Font.loadAsync()

这是我的 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

// 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"
    }
))

载入画面

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>
        )
    }
}

【问题讨论】:

    标签: react-native expo


    【解决方案1】:

    您需要将它们加载到App.js 内的_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')},
    
          ),
        ]);
      };
    

    然后在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>
          );
        }
      }
    

    【讨论】:

    • 我正在尝试这个,但现在应用程序加载时没有图标,然后显示此警告:[未处理的承诺拒绝:错误:字体家族名称为 '433B9F1D-F34D-4630-9A80-D47649A14EEC-feather'已加载
    • @WilPrim 好像你在调用 font.loadAsync 两次。
    【解决方案2】:

    我不知道你对FeatherFont的定义,

    但我不认为 Font 将其识别为字体。

    Font 是处理字体相关任务的模块。

    1. 首先,我们必须从资产目录加载字体,使用 Expo.Font.loadAsync()
    2. 我们可以在componentDidMount()生命周期方法中做到这一点 App 组件。
    3. App中添加如下方法:
    4. 现在我们已经将字体文件保存到磁盘和Font SDK 导入,让我们添加这段代码:

    我们需要一种在字体加载完成后重新渲染 Text 组件的方法。

    1. 首先我们在 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 });
      }
    }
    

    使用 React Native,您可以使用 fontFamily 样式属性在 Text 组件中指定字体。 fontFamily 是我们与Font.loadAsync 一起使用的密钥。

    用法

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-12-25
      • 1970-01-01
      • 2017-12-18
      • 2017-09-16
      • 1970-01-01
      • 1970-01-01
      • 2021-03-09
      相关资源
      最近更新 更多