尝试在 react 本机中使用文档选取器时无法读取未定义的属性(读取"pick")



我试图使用document picker为我的react-native应用程序。我尝试了这个命令来安装文档选择器:npm i react-native-document-picker。写了一些代码后,我首先在浏览器上打开我的应用程序。但是当我尝试点击按钮选择文件时,这个错误总是发生。有人能解决这个问题吗?

非常感谢大家。下面是我的代码示例

import React from 'react';
import {
View,
Button,
} from 'react-native';
import DocumentPicker from 'react-native-document-picker';

export default function App() {
const openDocument = async () => {
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)) {
// User cancelled the picker, exit any dialogs or menus and move on
} else {
throw err;
}
}
};
return (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<Button title="Choose file" onPress={() => openDocument()} />
</View>
);
}

尝试

console.log(res);

如果它不是NULL,你必须选择一个单一的文件,它将安全的JSON数组。

try {
const res = await DocumentPicker.pickSingle({
type: [DocumentPicker.types.allFiles],
});
console.log(
res.uri,
res.type, // mime type
res.name,
res.size
);
}

如果你选择DocumentPicker.pick,你必须做一个for循环

try {
const res = await DocumentPicker.pickSingle({
type: [DocumentPicker.types.allFiles],
});
for(i in res){
console.log(
i.uri,
i.type, // mime type
i.name,
i.size
);}
}

您正在使用pick函数。所以你会在数组中得到结果。如果你通过选择一个文件来选择拾取函数那么你可以通过这个

来获取值
const openDocument = async () => {
try {
const res = await DocumentPicker.pick({
type: [DocumentPicker.types.images],
});
console.log(
res[0].uri,
res[0].type, // mime type
res[0].size,
res[0].name
} catch (err) {
if (DocumentPicker.isCancel(err)) {
// User cancelled the picker, exit any dialogs or menus and move on
} else {
throw err;
}
}
};

或者你可以使用pickSingle函数

const openDocument = async () => {
try {
const res = await DocumentPicker.pickSingle({
type: [DocumentPicker.types.images],
});
console.log(
res.uri,
res.type, // mime type
res.name,
res.size,
);
} catch (err) {
if (DocumentPicker.isCancel(err)) {
// User cancelled the picker, exit any dialogs or menus and move on
} else {
throw err;
}
}
};