【问题标题】:How to deal with custom font and fontWeight with react-native如何用 react-native 处理自定义字体和 fontWeight
【发布时间】:2020-07-16 19:37:10
【问题描述】:

我设法在 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>

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

我该如何处理?

【问题讨论】:

标签: reactjs react-native fonts expo


【解决方案1】:

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

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;

【讨论】:

  • 谢谢!仅当您在条件匹配后删除 style.fontWeight 属性时,这才有效。您能否批准我的建议,以便我接受您的回答?
  • 其实你设置fontFamily字体粗细后并没有起作用!这是我的生产代码,运行良好!
  • 我同意。但如果我将它保留在 style var 上,它会回退到默认字体系列,而不是我设置的那个。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-01
  • 1970-01-01
  • 2023-03-26
  • 1970-01-01
  • 2021-04-11
相关资源
最近更新 更多