You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在React Native Expo应用中全局设置自定义字体

解决方案:Expo React Native全局设置字体并通过Tailwind控制字重

针对你遇到的问题,需要调整Tailwind配置并通过自定义组件实现全局字体设置,具体步骤如下:

1. 修正Tailwind配置

将不同字重的字体统一归到同一个fontFamily下,通过fontWeight映射到对应的字体文件(React Native会根据fontFamily + fontWeight匹配对应字体):

/** @type {import("tailwindcss").Config} */
module.exports = {
  presets: [require("@acme/tailwind-config")],
  content: ["./app/**/*.{js,jsx,ts,tsx}", "./components/**/*.{js,jsx,ts,tsx}"],
  theme: {
    extend: {
      fontFamily: {
        grotesk: ['"HK Grotesk"', "sans-serif"],
      },
      fontWeight: {
        normal: 'normal',   // 对应加载的"HK Grotesk"(Regular)
        medium: 'medium',   // 对应加载的"HK Grotesk-Medium"
        semibold: 'semibold', // 对应加载的"HK Grotesk-SemiBold"
        bold: 'bold',       // 对应加载的"HK Grotesk-Bold"
      },
    },
  },
};

2. 创建全局自定义Text组件(推荐)

由于React Native不支持样式继承,父组件样式无法自动传递给子Text组件,因此创建一个全局Text组件来默认应用字体:

import React from 'react';
import { Text, TextProps } from 'react-native';

export const GlobalText = (props: TextProps) => {
  // 默认应用HK Grotesk字体,同时保留传入的自定义样式
  return <Text {...props} style={[{ fontFamily: 'HK Grotesk' }, props.style]} />;
};

3. 在项目中使用

替换所有原生Text组件为GlobalText,并通过Tailwind类控制字重:

import { GlobalText } from './components/GlobalText';

// 使用示例
const ExampleScreen = () => {
  return (
    <View className="p-4">
      <GlobalText className="font-normal text-lg">常规字重文本</GlobalText>
      <GlobalText className="font-medium text-lg">中等字重文本</GlobalText>
      <GlobalText className="font-semibold text-lg">半粗体文本</GlobalText>
      <GlobalText className="font-bold text-lg">粗体文本</GlobalText>
    </View>
  );
};

备选方案:通过Tailwind全局base样式设置

如果不想自定义组件,可尝试在Tailwind配置中添加全局base样式(需确保NativeWind版本支持):

// 在tailwind.config.cjs中添加
module.exports = {
  // ...其他配置
  plugins: [
    function({ addBase }) {
      addBase({
        'Text': {
          fontFamily: '"HK Grotesk"',
        },
      });
    },
  ],
};

之后直接使用原生Text组件配合Tailwind字重类即可:

<Text className="font-medium">中等字重文本</Text>

注意:自定义Text组件的方式兼容性更好,避免因NativeWind版本差异导致全局样式不生效的问题。

内容的提问来源于stack exchange,提问作者ArthurDev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 01:27:20