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

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 15:18:04