React Native使用document picker时报Cannot read property 'pick' of undefined如何解决
你遇到的报错是因为react-native-document-picker仅支持Android、iOS原生端运行,未适配React Native Web环境,浏览器中调用它的API必然会触发异常。
解决方案
你可以按运行环境做分支适配,Web端直接调用浏览器原生的文件选择能力实现需求,改造后的参考代码如下:
import React, { useRef } from 'react'; import { View, Button, Platform } from 'react-native'; import DocumentPicker from 'react-native-document-picker'; export default function App() { // Web端隐藏文件输入框的引用 const fileInputRef = useRef(null); const openDocument = async () => { // 原生端走原有逻辑 if (Platform.OS !== 'web') { try { const res = await DocumentPicker.pick({ type: [DocumentPicker.types.allFiles], }); console.log( res.uri, res.type, // mime type res.name, res.size ); } catch (err) { if (DocumentPicker.isCancel(err)) { // 用户取消选择无需处理 } else { throw err; } } return; } // Web端触发原生文件选择框 fileInputRef.current?.click(); }; // Web端文件选择完成后的回调 const handleWebFileSelect = (e) => { const file = e.target.files[0]; if (!file) return; // 构造和原生端格式一致的返回结果,统一后续处理逻辑 const res = { uri: URL.createObjectURL(file), type: file.type, name: file.name, size: file.size }; console.log(res.uri, res.type, res.name, res.size); // 重置输入框,避免下次选择同个文件不触发回调 e.target.value = ''; }; return ( <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}> <Button title="Choose file" onPress={() => openDocument()} /> {/* Web端隐藏的原生文件输入框 */} {Platform.OS === 'web' && ( <input type="file" ref={fileInputRef} onChange={handleWebFileSelect} style={{ display: 'none' }} /> )} </View> ); }
如果你不想手动做多端适配,也可以替换为同时支持Web、Android、iOS的跨平台文件选择库,无需区分平台即可实现统一的文件选择能力。
内容的提问来源于stack exchange,提问作者anvuong
相关产品推荐
相关产品推荐

