How to deal with custom font and fontWeight with react-native

♀尐吖头ヾ 提交于 2020-05-17 05:49:18

问题


I managed to load custom font on my react-native expo app following the official documentation:

const App = () => {
  let [fontsLoaded] = useFonts({
    'Lato-Regular': require('../assets/fonts/Lato-Regular.ttf'),
    'Lato-Bold': require('../assets/fonts/Lato-Bold.ttf'),
    'Poppins-Light': require('../assets/fonts/Poppins-Light.ttf'),
    'Poppins-Bold': require('../assets/fonts/Poppins-Bold.ttf'),
  });

So I can use it with the component style:

<Text style={{
  fontFamily: 'Lato-Bold'
}}>Home page.</Text>

But I would like to use it like this:

<Text style={{
  fontFamily: 'Lato',
  fontWeight: 'bold',
}}>Home page.</Text>

This works for system fonts, but not with custom fonts.

How can I deal with it?


回答1:


You have to use custom component and extract the font weight from it. That's how it looks like

import React from 'react';
import { View, Text as RnText, StyleSheet } from 'react-native';

const Text = ({ style, children, ...rest }) => {
  let baseStyle = styles.medium;

  // Multiple styles may be provided.
  (Array.isArray(style) ? style : [style]).forEach((style) => {
    if (style && style.fontWeight) {
      baseStyle = style.fontWeight === 'bold' ? styles.bold : styles.medium;
    }
  });

  // We need to force fontWeight to match the right font family.
  return <RnText style={[baseStyle, style, { fontWeight: 'normal' }]} {...rest}>{children}</RnText>;
};

const styles = StyleSheet.create({
  bold: {
    fontFamily: 'Lato-Bold',
  },
  light: {
    fontFamily: 'Lato-Light',
  },
  medium: {
    fontFamily: 'Lato-Black',
  },
});

export default Text;


来源:https://stackoverflow.com/questions/61032122/how-to-deal-with-custom-font-and-fontweight-with-react-native

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!