React Native 应用添加外部字体时出现错误
Hey there! Let's work through this font issue you're facing in your first React Native app—that error message can be tricky, but it’s usually tied to how you’re setting up or referencing your custom fonts (or sometimes a mix-up in component imports). Let’s break down the most likely fixes step by step:
1. Make sure your fonts are properly linked/registered
React Native needs explicit setup to recognize custom fonts. Here’s how to get this right:
- First, create an
assets/fontsfolder in your project root and drop all your font files (likeRoboto-Regular.ttf) into it. - Add this snippet to your
package.jsonfile (at the root level, not nested inside any other object):"rnpm": { "assets": ["./assets/fonts/"] } - Run
npx react-native linkto let React Native copy the fonts to your iOS/Android project directories. For iOS, double-check that the fonts are listed in your Xcode project’s Copy Bundle Resources (under Build Phases). For Android, verify they’re inandroid/app/src/main/assets/fonts.
2. You might be using the wrong font name
This is a super common pitfall! A font’s filename doesn’t always match its internal "display name" that React Native requires. For example, a file named OpenSans-Regular.ttf might actually be called Open Sans internally.
- On macOS, open the font with Font Book to see its official name. On Windows, right-click the font > Properties > Details > Title.
- Update your StyleSheet to use this exact name:
const styles = StyleSheet.create({ pageText: { fontFamily: 'Open Sans', // Match the official font name here, not the filename! fontSize: 16, }, });
3. Check for component import/export mistakes in LandingPage
The error specifically calls out the LandingPage render method, so double-check if you’re importing any components (including custom text components that use the font) incorrectly:
- If a component uses a default export (like
export default CustomText;), import it without curly braces:import CustomText from './CustomText'; - If it uses a named export (like
export const CustomText = () => {...}), import it with curly braces:import { CustomText } from './CustomText'; - Make sure you didn’t accidentally misspell any component names in your render method.
4. Clear React Native’s cache
Sometimes old cache can cause weird asset loading glitches. Try resetting the cache and rebuilding your app:
- Stop your Metro server if it’s running.
- Run
npx react-native start --reset-cacheto start Metro with a fresh cache. - Rebuild your app: For iOS, run
npx pod-installthennpx react-native run-ios; for Android, runnpx react-native run-android.
If you’re still stuck, take a close look at the exact line in LandingPage where you’re using the custom font—chances are that’s where the mismatch is happening. Feel free to share more details if you need extra help!
内容的提问来源于stack exchange,提问作者user2995192

