react-native使用本地字体

139 阅读1分钟

1. 把字体放到src/assets/fonts

1.png

2. 安装react-native-asset

安装好了,执行 npx react-native-asset 可以看到字体被复制到android目录里面了

2.png

3.使用

注意,没有字重的字体不能和fontWeight一起使用,会导致fontFamily失效

const styles = StyleSheet.create({
  box: {
        fontFamily:'xuandong'
       }
})

4.封装,结合NativeWind

有字重的字体,可以根据fontWeight不同,挑选不同的字体展示,避免fontWeight导致的fontFamily失效

const Typography = {
  primary: 'yangrendong-Regular',
  thin: 'yangrendong-Light',
  extraLight: 'yangrendong-Light',
  light: 'yangrendong-Light',
  medium: 'yangrendong-Medium',
  semiBold: 'yangrendong-SemiBold',
  bold: 'yangrendong-Bold',
  extraBold: 'yangrendong-Bold',
  black: 'yangrendong-Bold',
};
const styles = StyleSheet.create({
  regular: {fontFamily: Typography.primary},
  thin: {fontFamily: Typography.thin},
  extraLight: {fontFamily: Typography.extraLight},
  light: {fontFamily: Typography.light},
  medium: {fontFamily: Typography.medium},
  semiBold: {fontFamily: Typography.semiBold},
  bold: {fontFamily: Typography.bold},
  extraBold: {fontFamily: Typography.extraBold},
  black: {fontFamily: Typography.black},
});
 
import {TextStyle as RNTextStyle} from 'react-native';
 

function processStyle(style: StyleProp<RNTextStyle>) {
  let weightedFontFamily: StyleProp<RNTextStyle> | undefined;
  if (style) {
    const {fontWeight, ...rest} = StyleSheet.flatten(style);
    if (fontWeight) {
      switch (fontWeight) {
        case '100':
          weightedFontFamily = styles.thin;
          break;
        case '200':
          weightedFontFamily = styles.extraLight;
          break;
        case '300':
          weightedFontFamily = styles.light;
          break;
        case '500':
          weightedFontFamily = styles.medium;
          break;
        case '600':
          weightedFontFamily = styles.semiBold;
          break;
        case 'bold':
        case '700':
          weightedFontFamily = styles.bold;
          break;
        case '800':
          weightedFontFamily = styles.extraBold;
          break;
        case '900':
          weightedFontFamily = styles.black;
          break;
        default:
          weightedFontFamily = styles.regular;
      }
    } else {
      weightedFontFamily = styles.regular;
    }
    return {rest, weightedFontFamily};
  } else {
    return {rest: {}, weightedFontFamily: styles.regular};
  }
}
 

export const StyledText = ({style, ...props}: StyledProps<TextProps>) => {
  const {rest, weightedFontFamily} = processStyle(style);
  return <Text style={[rest, weightedFontFamily]} {...props} />;
};
 

这时候使用的时候,即使加粗也不影响fontFamily

<StyledText className="text-2xl font-bold">AnimeDemo</StyledText>