为什么我的 PDF 没有在 React Native 中以模式显示?

问题描述 投票:0回答:0

我正在使用 Expo 构建一个 React Native 应用程序,我有一个模式,当用户点击文档时打开。模态包含一个使用 react-native-pdf 的 PDF 组件,并且当用户选择文档时动态设置源。但是,当我在我的 iPhone 上测试时,PDF 没有显示在模态中。我已经检查过 PDF 源是否正确并且组件正在接收它,但仍然没有显示任何内容。我该如何解决这个问题?

import React, { useEffect, useState, useContext } from "react";
import {
  View,
  Text,
  TouchableOpacity,
  StyleSheet,
  Modal,
  Pressable,
  Image,
  ScrollView,
  ActivityIndicator,
} from "react-native";
import Pdf from "react-native-pdf";
import axios from "axios";
import CompleteStudentContext from "../context/CompleteStudentContext";
import Icon from "react-native-vector-icons/MaterialIcons";
import { Dimensions } from "react-native";

const AlumnosScreen = () => {
  const { student, token } = useContext(CompleteStudentContext);
  const [cursos, setCursos] = useState([]);
  const [expandedCourseId, setExpandedCourseId] = useState(null);
  const [selectedAsignatura, setSelectedAsignatura] = useState(null);
  const [modalVisible, setModalVisible] = useState(false);
  const [showDocument, setShowDocument] = useState(false);
  const [selectedDocument, setSelectedDocument] = useState(null);
  const [documentModalVisible, setDocumentModalVisible] = useState(false);
  const [pdfSource, setPdfSource] = useState({}); // Inicializa pdfSource con un objeto vacío
  const [showPdf, setShowPdf] = useState(false);

  const [loading, setLoading] = useState(false);
  useEffect(() => {
    const fetchData = async () => {
      const cursosUrl = `http://localhost:3000/courses?studentId=${student._id}`;
      const cursosResponse = await axios.get(cursosUrl, {
        headers: {
          Authorization: `Bearer ${token}`,
        },
      });
      setCursos(cursosResponse.data);
    };
    fetchData();
  }, []);

  const handleCursoPress = async (cursoId) => {
    if (expandedCourseId === cursoId) {
      setExpandedCourseId(null);
      return;
    }
    setExpandedCourseId(cursoId);
  };

  const handleAsignaturaPress = (subject) => {
    setSelectedAsignatura(subject);
    setModalVisible(true);
  };
  // Agrega console.log en handleDocumentPress
  const handleDocumentPress = (document) => {
    console.log("handleDocumentPress iniciado");
    setSelectedDocument(document);
    setPdfSource({ uri: document.url });
    setModalVisible(false); // Cierra el primer modal (Asignatura)
    setDocumentModalVisible(true);
    console.log("handleDocumentPress completado");
  };

  return (
    <View style={styles.container}>
      <Text style={styles.title}>Cursos</Text>
      <View style={styles.coursesContainer}>
        {cursos.map((curso) => (
          <View key={curso._id}>
            <TouchableOpacity
              style={[
                styles.course,
                expandedCourseId === curso._id ? styles.courseExpanded : null,
              ]}
              onPress={() => handleCursoPress(curso._id)}
            >
              <Text style={styles.courseName}>{curso.name}</Text>
              <Icon
                name={
                  expandedCourseId === curso._id ? "expand-less" : "expand-more"
                }
                size={24}
                style={styles.courseIcon}
              />
            </TouchableOpacity>
            {expandedCourseId === curso._id && (
              <View style={styles.asignaturasContainer}>
                {curso.subjects.map((subject) => (
                  <TouchableOpacity
                    key={subject.name}
                    onPress={() => handleAsignaturaPress(subject)}
                    style={styles.subject}
                  >
                    <Text style={styles.asignaturaName}>{subject.name}</Text>
                  </TouchableOpacity>
                ))}
              </View>
            )}
          </View>
        ))}
      </View>

      <Modal
        animationType="slide"
        transparent={true}
        visible={modalVisible}
        onRequestClose={() => {
          setModalVisible(!modalVisible);
        }}
      >
        <View style={styles.centeredView}>
          <View style={styles.modalView}>
            <Text style={styles.modalTitle}>
              Asignatura: {selectedAsignatura?.name}
            </Text>
            <Image
              style={styles.modalImage}
              source={{ uri: selectedAsignatura?.image }}
            />
            <Text style={styles.modalDescription}>
              Descripción de la asignatura: {selectedAsignatura?.description}
            </Text>
            <ScrollView>
              {selectedAsignatura?.documents?.map((document, index) => (
                <TouchableOpacity
                  key={index}
                  style={styles.document}
                  onPress={() => handleDocumentPress(document)}
                >
                  <Text style={styles.documentTitle}>{document.title}</Text>
                  <Icon
                    name="picture-as-pdf"
                    size={24}
                    style={styles.documentIcon}
                  />
                </TouchableOpacity>
              ))}
            </ScrollView>
            <Pressable
              style={[styles.button, styles.buttonClose]}
              onPress={() => setModalVisible(!modalVisible)}
            >
              <Text style={styles.textStyle}>Cerrar</Text>
            </Pressable>
          </View>
        </View>
      </Modal>
      <View style={styles.container}>
        <Modal
          animationType="slide"
          transparent={true}
          visible={documentModalVisible}
          onRequestClose={() => {
            setDocumentModalVisible(false);
          }}
        >
          <View style={styles.centeredView}>
            <View style={styles.modalView}>
              <Text style={styles.modalTitle}>Documento PDF</Text>
              {loading && <ActivityIndicator size="large" color="#0000ff" />}
              {pdfSource.uri && (
                <Pdf
                  source={pdfSource}
                  onLoadComplete={(numberOfPages, filePath) => {
                    console.log(`Number of pages: ${numberOfPages}`);
                  }}
                  onPageChanged={(page, numberOfPages) => {
                    console.log(`Current page: ${page}`);
                  }}
                  onError={(error) => {
                    console.log(error);
                  }}
                  onPressLink={(uri) => {
                    console.log(`Link pressed: ${uri}`);
                  }}
                  style={styles.pdf}
                />
              )}
              <Pressable
                style={[styles.button, styles.buttonClose]}
                onPress={() => setDocumentModalVisible(false)}
              >
                <Text style={styles.textStyle}>Cerrar</Text>
              </Pressable>
            </View>
          </View>
        </Modal>
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#F5F5F5",
  },
  title: {
    fontSize: 24,
    fontWeight: "bold",
    textAlign: "center",
    marginTop: 10,
  },
  coursesContainer: {
    marginTop: 20,
  },
  course: {
    flexDirection: "row",
    alignItems: "center",
    backgroundColor: "#FFFFFF",
    borderRadius: 5,
    paddingHorizontal: 20,
    paddingVertical: 15,
    marginBottom: 10,
    elevation: 3,
  },
  courseExpanded: {
    borderBottomLeftRadius: 0,
    borderBottomRightRadius: 0,
  },
  courseName: {
    fontSize: 18,
    fontWeight: "bold",
    flexGrow: 1,
  },
  courseIcon: {
    color: "#555",
  },
  asignaturasContainer: {
    backgroundColor: "#FFFFFF",
    borderBottomLeftRadius: 5,
    borderBottomRightRadius: 5,
    paddingBottom: 10,
    marginBottom: 10,
    elevation: 3,
  },
  subject: {
    paddingHorizontal: 20,
    paddingVertical: 10,
  },
  asignaturaName: {
    fontSize: 16,
    color: "#555",
  },
  centeredView: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
    backgroundColor: "rgba(0, 0, 0, 0.4)",
  },
  modalView: {
    width: "80%",
    backgroundColor: "white",
    borderRadius: 20,
    padding: 35,
    alignItems: "center",
    shadowColor: "#000",
    shadowOffset: {
      width: 0,
      height: 2,
    },
    shadowOpacity: 0.25,
    shadowRadius: 4,
    elevation: 5,
  },
  modalTitle: {
    fontSize: 24,
    fontWeight: "bold",
    marginBottom: 10,
    textAlign: "center",
  },
  asignaturaImage: {
    width: 150,
    height: 150,
    borderRadius: 10,
    marginBottom: 10,
  },
  modalDescription: {
    fontSize: 16,
    marginBottom: 20,
    textAlign: "center",
  },
  button: {
    borderRadius: 20,
    padding: 10,
    elevation: 2,
    marginTop: 10,
  },
  buttonOpen: {
    backgroundColor: "#F194FF",
  },
  buttonClose: {
    backgroundColor: "#2196F3",
  },
  textStyle: {
    color: "white",
    fontWeight: "bold",
    textAlign: "center",
  },
  sideTag: {
    position: "absolute",
    top: 10,
    left: -5,
    paddingHorizontal: 5,
    paddingVertical: 3,
    backgroundColor: "#2196F3",
    borderTopRightRadius: 10,
    borderBottomRightRadius: 10,
  },
  sideTagText: {
    color: "white",
    fontWeight: "bold",
    fontSize: 25,
    textAlign: "center",
  },
  pdf: {
    flex: 1,
    width: Dimensions.get("window").width * 0.8,
    height: Dimensions.get("window").height * 0.5,
    marginBottom: 20,
  },
});

export default AlumnosScreen;

我已经验证了PDF的URL是正确的,也检查了Pdf组件的属性,但是还是没能解决问题

有谁知道会发生什么以及我该如何解决?非常感谢任何帮助。

不显示文件

react-native expo modal-dialog react-native-pdf
© www.soinside.com 2019 - 2024. All rights reserved.