如何使用 react-native 处理自定义字体和 fontWeight

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

official documentation:

之后,我成功地在我的 react-native expo 应用程序上加载了自定义字体
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'),
  });

所以我可以将它与组件样式一起使用:

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

但我想这样使用它:

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

这适用于系统字体,但不适用于自定义字体。

我该如何处理?

您必须使用自定义组件并从中提取字体粗细。原来是这样

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;