渲染的 FlatList 在 React Native 中不可滚动

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

基本上,我有一个反应本机选项卡来根据用户输入搜索可用房间,在用户提交输入后,应用程序将呈现可用房间的平面列表。问题是在我尝试提交输入后,平面列表实际上呈现了,但我无法向下滚动以查看呈现的平面列表,你们有什么想法可以修复它吗?顺便说一句,这是我的代码(我的代码部分使用印度尼西亚语,因此请忽略任何您无法理解的单词):

import {
  StyleSheet,
  View,
  SafeAreaView,
  Text,
  TextInput,
  TouchableWithoutFeedback,
  Keyboard,
  Button,
  FlatList,
  ScrollView,
} from "react-native";
import { useEffect, useState } from "react";
import DateTimePicker from "@react-native-community/datetimepicker";
import { Dropdown } from "react-native-element-dropdown";
import { format } from "date-fns";

const data = [
  { label: "Selasar", value: "selasar" },
  { label: "Kelas", value: "kelas" },
  { label: "Lab", value: "lab" },
];

export default function PinjamRuanganScreen() {
  const [tanggal, setTanggal] = useState(new Date());
  const [mulai, setMulai] = useState(new Date());
  const [selesai, setSelesai] = useState(new Date());
  const [jenis, setJenis] = useState(null);
  const [kapasitas, setKapasitas] = useState(0);
  const [searched, setSearched] = useState(false);
  const [result, setResult] = useState([]);

  const formatDate = (date) => {
    return format(date, "yyyy-MM-dd");
  };

  const formatTime = (date) => {
    const hours = date.getHours().toString().padStart(2, "0");
    const minutes = date.getMinutes().toString().padStart(2, "0");
    const formattedTime = `${hours}:${minutes}`;
    return formattedTime;
  };

  const changeDate = ({ type }, selectedDate) => {    if (type === "set") {
      const currentDate = selectedDate;
      setTanggal(currentDate);
    }
  };

  const changeMulai = ({ type }, selectedDate) => {    if (type === "set") {
      const currentDate = selectedDate;
      setMulai(currentDate);
    }
  };

  const changeSelesai = ({ type }, selectedDate) => {    if (type === "set") {
      const currentDate = selectedDate;
      setSelesai(currentDate);
    }
  };

  const handleSubmit = async () => {
    try {
      const response = await fetch(
        `http:(my-ip-address):4000/ruangan/cari-ruangan?jenis=${jenis}&tanggal=${formatDate(
          tanggal
        )}&mulai=${formatTime(mulai)}&selesai=${formatTime(
          selesai
        )}&kapasitas=${kapasitas}`
      );
      const data = await response.json();
      setResult(data.ruanganTersedia);
      setSearched(true);
      console.log(result.length);
    } catch (error) {
      console.log(error);
    }
  };

  return (
    <TouchableWithoutFeedback onPress={() => Keyboard.dismiss()}>
      <SafeAreaView style={styles.container}>
        <Text style={styles.label}>Tanggal peminjaman: </Text>
        <DateTimePicker
          value={tanggal}
          mode="date"
          onChange={changeDate}
          style={styles.timePicker}
        />
        <Text style={styles.label}>Dari jam: </Text>
        <DateTimePicker
          value={mulai}
          mode="time"
          onChange={changeMulai}
          style={styles.timePicker}
        />
        <Text style={styles.label}>Sampai jam: </Text>
        <DateTimePicker
          value={selesai}
          mode="time"
          onChange={changeSelesai}
          style={styles.timePicker}
        />
        <Dropdown
          style={styles.dropdown}
          maxHeight={300}
          itemContainerStyle={{ width: 600 }}
          data={data}
          labelField={"label"}
          valueField={"value"}
          placeholder="Pilih jenis ruangan"
          value={jenis}
          onChange={(value) => setJenis(value.value)}
          renderItem={(item) => {
            return (
              <View style={styles.item}>
                <Text>{item.label}</Text>
              </View>
            );
          }}
        />
        <Text>Kapasitas:</Text>

        <TextInput
          style={styles.textInput}
          keyboardType="numeric"
          value={kapasitas}
          onChangeText={setKapasitas}
        />
        <Button title="Cari ruangan" onPress={handleSubmit} />

        {!searched ? (
          <Text>Hasil pencarian ruangan akan ditampilkan disini</Text>
        ) : result.length === 0 ? (
          <>
            <Text>
              Tidak ada ruangan yang sesuai dengan kriteria yang anda inginkan
            </Text>
          </>
        ) : (
          <View>
            <FlatList
              data={result}
              renderItem={({ item }) => {
                return (
                  <View style={styles.card}>
                    <Text style={styles.namaRuangan}>{item.nama}</Text>
                    <Text style={styles.detailRuangan}>{item.jenis}</Text>
                    <Text style={styles.detailRuangan}>{item.kapasitas}</Text>
                    <Text style={styles.detailRuangan}>{item.lantai}</Text>
                  </View>
                );
              }}
              keyExtractor={(item) => item._id}
              ItemSeparatorComponent={<View style={{ height: 24 }} />}
              ListHeaderComponent={
                <View style={{ marginTop: 20, marginBottom: 20 }}>
                  <Text
                    style={{
                      alignSelf: "center",
                      fontSize: 30,
                      fontWeight: "bold",
                    }}
                  >
                    Ruangan yang tersedia
                  </Text>
                </View>
              }
            />
          </View>
        )}
      </SafeAreaView>
    </TouchableWithoutFeedback>
  );
}

const styles = StyleSheet.create({
  container: {
    padding: 24,
    justifyContent: "center",
    alignItems: "center",
  },
  dropdown: {
    margin: 16,
    height: 50,
    alignSelf: "stretch",
    borderBottomColor: "gray",
    borderBottomWidth: 0.5,
  },
  item: {
    padding: 17,
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "center",
  },
  label: {
    marginBottom: 10,
  },
  timePicker: {
    marginBottom: 20,
  },
  textInput: {
    borderWidth: 1,
    borderStyle: "solid",
    width: 50,
  },
  card: {
    backgroundColor: "white",
    padding: 16,
    borderRadius: 8,
    borderWidth: 1,
  },
  namaRuangan: {
    fontSize: 30,
  },
  detailRuangan: {
    fontSize: 24,
    color: "#666666",
  },
});

这是应用程序的屏幕截图(在 ios 中使用 expo go): 提交前:

The screen before sumbitting

提交后(在这种状态下,屏幕就像这样卡住,我无法向下滚动查看平面列表的其余部分,甚至无法向上滚动查看屏幕的上部): The screen after submitting

我希望 FlatList 是可滚动的

javascript css react-native react-native-flatlist
1个回答
0
投票
  • 为了确保 SafeAreaView 占据屏幕的整个高度,我已将
     flex: 1
    添加到
    container
  • 为了确保 FlatList 可以占用剩余空间并且可以滚动,我们将
    FlatList
    包裹在
    ScrollView
    中。
  • 为了确保 FlatList 增长以填充可用空间,我将
    flex: 1
    添加到
    FlatList

By making these changes FlatList is scrollable

import {
  StyleSheet,
  View,
  SafeAreaView,
  Text,
  TextInput,
  TouchableWithoutFeedback,
  Keyboard,
  Button,
  FlatList,
  ScrollView,
} from "react-native";
import { useState } from "react";
import DateTimePicker from "@react-native-community/datetimepicker";
import { Dropdown } from "react-native-element-dropdown";
import { format } from "date-fns";

const data = [
  { label: "Selasar", value: "selasar" },
  { label: "Kelas", value: "kelas" },
  { label: "Lab", value: "lab" },
];

export default function PinjamRuanganScreen() {
  const [tanggal, setTanggal] = useState(new Date());
  const [mulai, setMulai] = useState(new Date());
  const [selesai, setSelesai] = useState(new Date());
  const [jenis, setJenis] = useState(null);
  const [kapasitas, setKapasitas] = useState(0);
  const [searched, setSearched] = useState(false);
  const [result, setResult] = useState([]);

  const formatDate = (date) => format(date, "yyyy-MM-dd");

  const formatTime = (date) => {
    const hours = date.getHours().toString().padStart(2, "0");
    const minutes = date.getMinutes().toString().padStart(2, "0");
    return `${hours}:${minutes}`;
  };

  const changeDate = ({ type }, selectedDate) => {
    if (type === "set") {
      setTanggal(selectedDate);
    }
  };

  const changeMulai = ({ type }, selectedDate) => {
    if (type === "set") {
      setMulai(selectedDate);
    }
  };

  const changeSelesai = ({ type }, selectedDate) => {
    if (type === "set") {
      setSelesai(selectedDate);
    }
  };

  const handleSubmit = async () => {
    try {
      const response = await fetch(
        `http://(my-ip-address):4000/ruangan/cari-ruangan?jenis=${jenis}&tanggal=${formatDate(
          tanggal
        )}&mulai=${formatTime(mulai)}&selesai=${formatTime(
          selesai
        )}&kapasitas=${kapasitas}`
      );
      const data = await response.json();
      setResult(data.ruanganTersedia);
      setSearched(true);
    } catch (error) {
      console.log(error);
    }
  };

  return (
    <TouchableWithoutFeedback onPress={() => Keyboard.dismiss()}>
      <SafeAreaView style={styles.container}>
        <ScrollView contentContainerStyle={{ flexGrow: 1 }}>
          <View style={styles.innerContainer}>
            <Text style={styles.label}>Tanggal peminjaman: </Text>
            <DateTimePicker
              value={tanggal}
              mode="date"
              onChange={changeDate}
              style={styles.timePicker}
            />
            <Text style={styles.label}>Dari jam: </Text>
            <DateTimePicker
              value={mulai}
              mode="time"
              onChange={changeMulai}
              style={styles.timePicker}
            />
            <Text style={styles.label}>Sampai jam: </Text>
            <DateTimePicker
              value={selesai}
              mode="time"
              onChange={changeSelesai}
              style={styles.timePicker}
            />
            <Dropdown
              style={styles.dropdown}
              maxHeight={300}
              itemContainerStyle={{ width: 600 }}
              data={data}
              labelField={"label"}
              valueField={"value"}
              placeholder="Pilih jenis ruangan"
              value={jenis}
              onChange={(value) => setJenis(value.value)}
              renderItem={(item) => (
                <View style={styles.item}>
                  <Text>{item.label}</Text>
                </View>
              )}
            />
            <Text>Kapasitas:</Text>
            <TextInput
              style={styles.textInput}
              keyboardType="numeric"
              value={kapasitas.toString()}
              onChangeText={setKapasitas}
            />
            <Button title="Cari ruangan" onPress={handleSubmit} />

            {!searched ? (
              <Text>Hasil pencarian ruangan akan ditampilkan disini</Text>
            ) : result.length === 0 ? (
              <Text>
                Tidak ada ruangan yang sesuai dengan kriteria yang anda inginkan
              </Text>
            ) : (
              <FlatList
                style={styles.flatList}
                data={result}
                renderItem={({ item }) => (
                  <View style={styles.card}>
                    <Text style={styles.namaRuangan}>{item.nama}</Text>
                    <Text style={styles.detailRuangan}>{item.jenis}</Text>
                    <Text style={styles.detailRuangan}>{item.kapasitas}</Text>
                    <Text style={styles.detailRuangan}>{item.lantai}</Text>
                  </View>
                )}
                keyExtractor={(item) => item._id}
                ItemSeparatorComponent={<View style={{ height: 24 }} />}
                ListHeaderComponent={
                  <View style={{ marginTop: 20, marginBottom: 20 }}>
                    <Text
                      style={{
                        alignSelf: "center",
                        fontSize: 30,
                        fontWeight: "bold",
                      }}
                    >
                      Ruangan yang tersedia
                    </Text>
                  </View>
                }
              />
            )}
          </View>
        </ScrollView>
      </SafeAreaView>
    </TouchableWithoutFeedback>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  innerContainer: {
    padding: 24,
    justifyContent: "center",
    alignItems: "center",
  },
  dropdown: {
    margin: 16,
    height: 50,
    alignSelf: "stretch",
    borderBottomColor: "gray",
    borderBottomWidth: 0.5,
  },
  item: {
    padding: 17,
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "center",
  },
  label: {
    marginBottom: 10,
  },
  timePicker: {
    marginBottom: 20,
  },
  textInput: {
    borderWidth: 1,
    borderStyle: "solid",
    width: 50,
  },
  card: {
    backgroundColor: "white",
    padding: 16,
    borderRadius: 8,
    borderWidth: 1,
  },
  namaRuangan: {
    fontSize: 30,
  },
  detailRuangan: {
    fontSize: 24,
    color: "#666666",
  },
  flatList: {
    flex: 1,
  },
});

© www.soinside.com 2019 - 2024. All rights reserved.