首页 > 解决方案 > 将自定义字体导入单独的 Styles.js 文件

问题描述

我正在尝试将自定义字体导入到特定于样式的 Styles.js 文件中。该字体当前已导入主 App.js 文件,但不知何故我无法在 Styles.js 中使用它。

我在 App.js 中使用的代码:

import React from "react";
import { View } from "react-native";
import Gamefrom "./components/Game.js";
import { AppLoading } from 'expo';
import * as Font from 'expo-font';

export let customFonts = {
  'headline': require('../assets/fonts/MonotypeCorsivaRegular.ttf'),
};


export class App extends React.Component {

  state = {
    fontsLoaded: false,
  };

  async _loadFontsAsync() {
    await Font.loadAsync(customFonts);
    this.setState({ fontsLoaded: true });
  }

  componentDidMount() {
    this._loadFontsAsync();
  }


  render() {
    if (this.state.fontsLoaded) {
      return (
        <View>
          <View>
            <Game/>
          </View>
        </View>
      );
    }  else {
      return <AppLoading />;
    }
  }
};

export default App;

我在 Styles.js 中的代码:

import { StyleSheet } from "react-native";

export const styles = StyleSheet.create({
    headline: {
      fontSize: 35,
      color: "black",
      fontWeight: "bold",
      fontFamily: "headline"
    },
})

标签: javascriptreact-native

解决方案


我认为问题在于您导入自定义字体的方式和实现方式App.js

请尝试如下。

App.js

import React from "react";
import { View } from "react-native";
import Gamefrom "./components/Game.js";
import { AppLoading } from 'expo';
import * as Font from 'expo-font';


export default class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      fontsLoaded: false,
    };
  }

  async _loadFontsAsync() {
    await Font.loadAsync({
      'headline': require('../assets/fonts/MonotypeCorsivaRegular.ttf'),
    });
    this.setState({ fontsLoaded: true });
  }

  componentDidMount() {
    this._loadFontsAsync();
  }


  render() {
    if (this.state.fontsLoaded) {
      return (
        <View>
          <View>
            <Game/>
          </View>
        </View>
      );
    }
    else {
      return <AppLoading />;
    }
  }
};

Style.js不需要任何更改。


推荐阅读