如何使用 react-native 处理自定义字体和 fontWeight [英] How to deal with custom font and fontWeight with react-native

查看:25
本文介绍了如何使用 react-native 处理自定义字体和 fontWeight的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我设法按照 官方文档:

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>

但我想这样使用它:

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

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

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

我该如何处理?

推荐答案

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

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;

这篇关于如何使用 react-native 处理自定义字体和 fontWeight的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆