React Native + Tailwind CSS自定义字体异常:仅Rajdhani Bold生效
Expo + React Native + Tailwind CSS 中 Rajdhani 字体仅Bold字重生效问题
首次使用React Native和Tailwind CSS开发应用,导入Rajdhani字体家族后,在iOS设备的Expo预览中仅Rajdhani Bold字体能够正常显示,其余字重(Regular、SemiBold、Light、Medium)均无法生效。将font-rSemiBold替换为font-rBold时字体可正常显示,但其余字重均无效。已尝试调整配置文件中自定义字体名称的引号格式,也确认了字体文件名和ttf文件本身无问题,但均未解决。
当前代码文件
index.js
import { StatusBar } from "expo-status-bar"; import { Text, View} from "react-native"; import { Link } from "expo-router"; export default function App(){ return( <View className="flex-1 items-center justify-center bg-white"> <Text className="text-3xl font-rSemiBold">Test test</Text> <StatusBar style="auto" /> <Link href="/sign-in" style={{color: 'blue'}}>Proceed to Login</Link> </View> ); }
tailwind.config.js
/** @type {import('tailwindcss').Config} */ module.exports = { content: ["./app/**/*.{js,jsx,ts,tsx}", "./components/**/*.{js,jsx,ts,tsx}"], theme: { extend: { colors: { primary: '#D0E358' } }, fontFamily: { rRegular: ["Rajdhani-Regular", "sans-serif"], rBold: ["Rajdhani-Bold", "sans-serif"], rSemiBold: ["Rajdhani-SemiBold", "sans-serif"], rLight: ["Rajdhani-Light", "sans-serif"], rMedium: ["Rajdhani-Medium", "sans-serif"] } }, plugins: [], }
字体文件结构
字体文件存放于assets/fonts目录下,包含对应字重的Rajdhani .ttf文件(Rajdhani-Regular.ttf、Rajdhani-Bold.ttf等)。
解决方案
确保所有字体通过expo-font完成加载
Expo项目中需显式加载所有字体,单独加载Bold字重会导致其他字重未注册。在App入口添加字体加载逻辑:import { useFonts } from 'expo-font'; import AppLoading from 'expo-app-loading'; export default function App() { const [fontsLoaded] = useFonts({ 'Rajdhani-Regular': require('./assets/fonts/Rajdhani-Regular.ttf'), 'Rajdhani-Bold': require('./assets/fonts/Rajdhani-Bold.ttf'), 'Rajdhani-SemiBold': require('./assets/fonts/Rajdhani-SemiBold.ttf'), 'Rajdhani-Light': require('./assets/fonts/Rajdhani-Light.ttf'), 'Rajdhani-Medium': require('./assets/fonts/Rajdhani-Medium.ttf'), }); if (!fontsLoaded) { return <AppLoading />; } // 原App组件内容 return( <View className="flex-1 items-center justify-center bg-white"> <Text className="text-3xl font-rSemiBold">Test test</Text> <StatusBar style="auto" /> <Link href="/sign-in" style={{color: 'blue'}}>Proceed to Login</Link> </View> ); }将自定义字体配置移至theme.extend下
当前fontFamily直接定义在theme根节点,会覆盖Tailwind默认字体配置,可能导致非Bold字重的映射失效。调整tailwind.config.js:module.exports = { content: ["./app/**/*.{js,jsx,ts,tsx}", "./components/**/*.{js,jsx,ts,tsx}"], theme: { extend: { colors: { primary: '#D0E358' }, fontFamily: { rRegular: ["Rajdhani-Regular", "sans-serif"], rBold: ["Rajdhani-Bold", "sans-serif"], rSemiBold: ["Rajdhani-SemiBold", "sans-serif"], rLight: ["Rajdhani-Light", "sans-serif"], rMedium: ["Rajdhani-Medium", "sans-serif"] } }, }, plugins: [], }核对iOS字体内部名称
iOS系统中字体的内部PostScript名称可能与文件名不一致,可通过Mac的Font Book工具查看字体的真实名称,确保配置中的字体名称与真实名称完全匹配。清除Expo缓存
运行expo r -c命令清除项目缓存,重新加载应用,避免缓存导致的字体加载异常。
内容的提问来源于stack exchange,提问作者wickedwhite
相关产品推荐
相关产品推荐

