在这里反应Native newb!
我正在尝试使用expo在我的本机应用程序中使用自定义字体。我尝试按照https://docs.expo.io/versions/latest/guides/using-custom-fonts.html#using-custom-fonts的说明操作,但没有运气。
这是我的App.js:
import React from 'react';
import { View, Text, TouchableOpacity, TextInput, StyleSheet, AsyncStorage, Alert, Platform, NativeModules } from 'react-native';
import { Expo } from 'expo';
import { StackNavigator } from 'react-navigation';
import LoginScreen from './src/views/LoginScreen';
import AuthenticatedScreen from './src/views/AuthenticatedScreen';
import './ReactotronConfig'
import styles from './src/styles/ParentStyles'
const { StatusBarManager } = NativeModules;
const RootStack = StackNavigator(
{
Login: { screen: LoginScreen },
Authenticated: { screen: AuthenticatedScreen }
},
{ initialRouteName: 'Login'}
);
const STATUSBAR_HEIGHT = Platform.OS === 'ios' ? 20 : StatusBarManager.HEIGHT;
export default class App extends React.Component {
state = {
fontLoaded: false,
};
async componentDidMount() {
await Expo.Font.loadAsync({
'open-sans-bold': require('./src/assets/fonts/OpenSans-Bold.ttf'),
});
console.log('running')
this.setState({ fontLoaded: true });
}
render() {
console.log('statusBarHeight: ' + StatusBarManager.HEIGHT);
return (<RootStack />);
}
}
console.disableYellowBox = true;
我试图在我的登录页面中调用open-sans-bold
,如下所示:
render() {
return (
<View style = { parentStyles.container } >
<View style={ loginStyles.backgroundImageContainer }>
<Image style={ loginStyles.backgroundImage } source={require('../assets/img/splash.png')} />
</View>
<View style={ loginStyles.logoImageContainer } >
<Image style={ loginStyles.logoImage } source={require('../assets/img/PMlogo.png')} resizeMode="contain"/>
</View>
<View style={{flex: 50 }} >
//***CALLING FONT HERE***
<Text style={{ fontFamily: 'open-sans-bold', fontSize: 56 }}>Email</Text>
<TextInput style = {loginStyles.input}
underlineColorAndroid = "transparent"
placeholder = "Email"
placeholderTextColor = "red"
autoCapitalize = "none"
ref = { input => { this.textInputEmail = input }}
onChangeText = { this.handleEmail }/>
<TextInput style = { loginStyles.input }
underlineColorAndroid = "transparent"
placeholder = "Password"
placeholderTextColor = "red"
autoCapitalize = "none"
ref = { input => { this.textInputPassword = input }}
onChangeText = { this.handlePassword }/>
<TouchableOpacity
style = {loginStyles.submitButton}
onPress = { () => this.login(this.state.email, this.state.password) }
>
<Text style = { loginStyles.submitButtonText }> Login </Text>
</TouchableOpacity>
</View>
</View>
)
}
不幸的是,当我运行此操作时,我收到以下错误:
fontFamily 'open-sans-bold' is not a system font and has not been loaded through Expo.Font.loadAsync.
- If you intended to use a system font, make sure you typed the name correctly and that it is supported by your device operating system.
- If this is a custom font, be sure to load it with Expo.Font.loadAsync.
任何帮助都非常赞赏!!
答案 0 :(得分:0)
嘿,兄弟,这是app.js的正常工作代码,只适合您的情况
import React from "react";
import { AppLoading, Font } from "expo";
import { StyleSheet, Text, View } from "react-native";
export default class App extends React.Component {
state = {
loaded: false,
};
componentWillMount() {
this._loadAssetsAsync();
}
_loadAssetsAsync = async () => {
await Font.loadAsync({
diplomata: require("./assets/fonts/DiplomataSC-Regular.ttf"),
});
this.setState({ loaded: true });
};
render() {
if (!this.state.loaded) {
return <AppLoading />;
}
return (
<View style={styles.container}>
<Text style={styles.info}>
Look, you can load this font! Now the question is, should you use it?
Probably not. But you can load any font.
</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: "#fff",
alignItems: "center",
justifyContent: "center",
padding: 30,
},
info: {
fontFamily: "diplomata",
textAlign: "center",
fontSize: 14,
},
});
答案 1 :(得分:0)
如果您正在使用expo,则应按以下方式导入Font和AppLoading:
import { Font, AppLoading } from "expo";
下一步,在根组件中创建一个常量(不在组件块中,可能在根组件的顶部),如下所示:
const fetchFonts = () => {
return Font.loadAsync({
"open-sans": require("./assets/fonts/OpenSans-Regular.ttf"),
"open-sans-bold": require("./assets/fonts/OpenSans-Bold.ttf")
});
};
现在在根组件中:
export default function App() {
const [fontLoaded, setFontLoaded] = useState(false);
if (!fontLoaded) {
return (
<AppLoading
startAsync={fetchFonts}
onFinish={() => {
setFontLoaded(true);
}}
/>
);
}
return (
<Provider store={store}>
<ShopNavigator />
</Provider>
);
}
您的根组件(本课程中的App.js)最后应该像这样:
import React, { useState } from "react";
import { createStore, combineReducers } from "redux";
import { Provider } from "react-redux";
import { Font, AppLoading } from "expo";
import productsReducer from "./store/reducers/products";
import ShopNavigator from "./navigation/ShopNavigator";
const rootReducer = combineReducers({
products: productsReducer
});
const store = createStore(rootReducer);
const fetchFonts = () => {
return Font.loadAsync({
"open-sans": require("./assets/fonts/OpenSans-Regular.ttf"),
"open-sans-bold": require("./assets/fonts/OpenSans-Bold.ttf")
});
};
export default function App() {
const [fontLoaded, setFontLoaded] = useState(false);
if (!fontLoaded) {
return (
<AppLoading
startAsync={fetchFonts}
onFinish={() => {
setFontLoaded(true);
}}
/>
);
}
return (
<Provider store={store}>
<ShopNavigator />
</Provider>
);
}
答案 2 :(得分:0)
出于某种奇怪的原因,功能组件方法对我不起作用,我需要更改为类组件。
这是基于 React Native Cookbook 的最低工作示例:
import React from 'react';
import { AppLoading } from 'expo';
import * as Font from 'expo-font';
import YourComponent from 'path/to/component';
export default class App extends React.Component {
state = {
fontLoaded: false
};
async componentDidMount() {
await Font.loadAsync({
'open-sans': require('./assets/fonts/OpenSans-Regular.ttf'),
'open-sans-bold': require('./assets/fonts/OpenSans-Bold.ttf')
});
this.setState({ fontLoaded: true });
}
render() {
return this.state.fontLoaded ? <YourComponent /> : <AppLoading />;
}
}
注意:使用componentWillMount
可以引发错误,因为不能保证等待我们的Font.loadAsync
完成。另外,使用componentDidMount
不会阻止应用的初始呈现。
答案 3 :(得分:0)
请使用以下命令升级您的博览会
expo upgrade
Expo应该大于36.0.0,否则尝试使用npm install expo@36.0.1