如何使用react native禁用onPress平面列表项?

jljoyd4f  于 2023-03-13  发布在  React
关注(0)|答案(1)|浏览(146)

我有一个平面列表,我想在data.subcategories.length == 0时禁用onPress函数,这样用户就不能再点击了,因为如果用户点击了最后一个条目,平面列表中就没有条目了。
这是一个组件:

export const SubCategoryScreen = ({ route, navigation }) => {
    const [subCatgoryList, setSubCategoryList] = useState([]);
    const [isLoading, setLoading] = useState(true);

    useEffect(() => {
        fetchSubCategoryData(route.params.subcategories).then((data) => {
            if (data.animals.length > 0) {
                setSubCategoryList(data.animals);
                setLoading(false);
            } else {
                setSubCategoryList(data.subcategories);
                setLoading(false);
            }
        });
    }, [route]);

    return (
        <SafeArea>
            {isLoading && (
                <LoadingContainer>
                    <ActivityIndicator animating={true} color={MD2Colors.green200} />
                </LoadingContainer>
            )}
            <CategoryList
                data={subCatgoryList}
                renderItem={({ item }) => {
                    return (
                        <TouchableOpacity
                            onPress={() => navigation.navigate("groepen", { subcategories: item.id })}>
                            <Spacer position="bottom" size="large">
                                <SubCategoryInfoCard subcategories={item} />
                            </Spacer>
                        </TouchableOpacity>
                    );
                }}
                keyExtractor={(item) => item.id}
            />
        </SafeArea>
    );
};

问题:data.subcategories.length == 0时如何禁用onPress

sczxawaw

sczxawaw1#

尝试将disabled prop 添加到您的TouchableOpacity组件:

<CategoryList
  data={subCatgoryList}
  renderItem={({ item, index }) => {
    return (
      <TouchableOpacity
        onPress={() => navigation.navigate("groepen", { subcategories: item.id })}
        disabled={loading || index === subCatgoryList.length - 1}
       >
         <Spacer position="bottom" size="large">
         <SubCategoryInfoCard subcategories={item} />
         </Spacer>
       </TouchableOpacity>
     );
  }}
  keyExtractor={(item) => item.id}
/>

相关问题