React Native集成react-native-pdf遇模块解析及初始化错误求助
解决方案
问题核心是Expo Go不支持直接引入含原生代码的第三方库,react-native-pdf和react-native-blob-util均包含原生模块,无法在Expo Go的沙箱环境中正常初始化,因此引发报错。以下是两种可行解决路径:
路径一:改用Expo兼容的纯JS方案(推荐)
用react-native-webview替代react-native-pdf,WebView支持直接渲染Base64格式的PDF,且无需原生依赖,完全适配Expo Go环境。
- 卸载冲突依赖
npm uninstall react-native-pdf react-native-blob-util # 或使用yarn yarn remove react-native-pdf react-native-blob-util
- 修改代码替换PDFView为WebView
import React, { FunctionComponent, useEffect, useState } from "react"; import { StyleSheet, View, ActivityIndicator } from 'react-native'; import { StackNavigationProp } from "@react-navigation/stack"; import { RouteProp } from "@react-navigation/native"; import { FundStackParamsList } from "../../navigation/Params"; import { useTheme } from '../../theme'; import { EdgeInsets, useSafeAreaInsets } from 'react-native-safe-area-context'; import { Endpoints, getTokens } from "../../api"; import WebView from 'react-native-webview'; interface ReportViewScreenProps { navigation: StackNavigationProp<FundStackParamsList, 'HistoricReportsView'>; route: RouteProp<FundStackParamsList, 'HistoricReportsView'>; } const HistoricReportViewScreen: FunctionComponent<ReportViewScreenProps> = (props) => { const theme = useTheme(), edgeInsets = useSafeAreaInsets(), style = styles(theme, edgeInsets); const [pdfData, setPdfData] = useState<string | null>(null); useEffect(() => { getTokens() .then((token) => { fetch(Endpoints.FUND_REPORT_FILE(props.route.params.refID), { method: 'GET', headers: { 'Authorization': `Bearer ${token.access}`, }, }) .then((response) => response.blob()) .then((blob) => { const reader = new FileReader(); reader.onloadend = () => { // readAsDataURL会直接生成完整的data URI,无需手动拼接 setPdfData(reader.result as string); }; reader.readAsDataURL(blob); }) .catch((error) => { console.error('获取PDF失败:', error); }); }); }, [props.route.params.refID]); return ( <View style={style.container}> {pdfData ? ( <WebView source={{ uri: pdfData }} onLoad={() => console.log('PDF加载完成')} onError={(error) => console.error('加载PDF出错:', error)} style={{ flex: 1 }} javaScriptEnabled={true} domStorageEnabled={true} /> ) : ( <ActivityIndicator size="large" color={theme.colors.primary} /> )} </View> ); }; const styles = (theme: ReturnType<typeof useTheme>, edgeInsets: EdgeInsets) => StyleSheet.create({ container: { flex: 1, backgroundColor: theme.colors.background, }, // ...其他样式 }); export default HistoricReportViewScreen;
路径二:构建自定义Expo Dev Client(保留react-native-pdf)
如果必须使用react-native-pdf,需要创建自定义开发客户端来支持原生模块:
- 安装Expo Dev Client
expo install expo-dev-client
- 清理并预构建原生项目
expo prebuild --clean
- 构建并运行自定义开发包
# iOS expo run:ios # Android expo run:android
- 重新安装依赖
npm install react-native-pdf react-native-blob-util # 或yarn yarn add react-native-pdf react-native-blob-util
之后使用自定义开发包运行项目,即可正常加载原生模块。
内容的提问来源于stack exchange,提问作者Mohsin Ghafoor
相关产品推荐
相关产品推荐

