【问题标题】:Filtering items when a feild is pressed in react native在本机反应中按下字段时过滤项目
【发布时间】:2020-06-21 01:26:38
【问题描述】:

我有一个带有不同卡片(有文章信息)的屏幕,我试图在按下方便的类别时按类别过滤文章我希望选择该类别并显示属于该类别的文章,另一方面,所有类别的所有文章都在未选择类别时显示(如果您看下面的图片,这将更有意义)

用于显示不同类别图片的代码:

import TouchableScale from "react-native-touchable-scale";
import { category } from "../api/data";

import colors from "../config/colors";

function HotTopics({ navigation }) {
  //const { width, height } = Dimensions.get("window");
  return (
    <View style={styles.Container}>
      <View>
        <Text style={styles.CategoryText}>Hot Topics</Text>
      </View>
      <FlatList
        horizontal
        showsHorizontalScrollIndicator={false}
        style={{ paddingHorizontal: 15 }}
        data={category}
        keyExtractor={(item) => item.id}
        renderItem={({ item }) => {
          return (
            <View>
              <View>
                <TouchableScale
                  activeScale={0.9}
                  tension={50}
                  friction={7}
                  useNativeDriver
                  onPress={() => navigation.navigate({ id: item.id })}
                >
                  {/* to show the horizental news list*/}

                  <Image
                    source={{ uri: item.image }}
                    style={{
                      width: 100,
                      height: 120,
                      borderRadius: 16,
                      marginRight: 10,
                    }}
                  />

                  {/* to show the news titles inside the pictures*/}
                  <SharedElement
                    id={`item.${item.id}.text`}
                    style={{
                      width: 100,
                      position: "absolute",
                      bottom: 95,
                      //left: 10,
                      paddingHorizontal: 5,
                      justifyContent: "center",
                      alignItems: "center",
                    }}
                  >
                    <Text style={styles.blogTitle}>{item.title}</Text>
                  </SharedElement>
                  {/* to show the pictre of the author of the news article*/}

                  {/* to show the name of the author and read time of article*/}
                </TouchableScale>
              </View>
            </View>
          );
        }}
      />
    </View>
  );
}

用于显示文章卡片的代码如下:(ArticleList.js)

function ArticleList({ navigation, post }) {
  if (!post.length) {
    return null;
  } // so we dont show anything untill we have articles
  return (
    <>
      <View style={styles.Container}>
        <Text style={styles.HeadText}>Popular</Text>
        <Text style={styles.subText}>Show all</Text>
      </View>
      <FlatList
        showsVerticalScrollIndicator={false}
        data={post}
        keyExtractor={(item) => item.id}
        renderItem={({ item }) => {
          return (
            <TouchableScale
              activeScale={0.9}
              tension={50}
              friction={7}
              useNativeDriver
              onPress={() =>
                navigation.navigate("DetailScreen", { data: item })
              }
            >
              <Card item={item} />
            </TouchableScale>
          );
        }}
      />
    </>
  );
}

在主屏幕上我调用 ArticleList.js 并像这样过滤数据:

// for filtering the data 
const filterResultsByCategory = (category) => {
    return post.filter((onepost) => {
      return onepost.category === category;
    });
  };
// to show the data 
<ArticleListVer post={filterResultsByCategory("Politics")} />

用于主屏幕的代码:

import React, { useState } from "react";
import { StyleSheet, View, ScrollView, SafeAreaView } from "react-native";
import Header from "../components/Header";
import ArticleList from "../components/ArticleList";
import ArticleListVer from "../components/ArticleListVer";
import Categories from "../components/Categories";
import HotTopics from "../components/HotTopics";
import { LinearGradient } from "expo-linear-gradient";
import useArticles from "../hooks/useArticles";
import usePosts from "../hooks/usePosts";
function MainScreen({ navigation }) {
  const [Category, setCategory] = useState();
  const [loadApi, data, errorMessage] = useArticles();
  const [loadPost, post] = usePosts();
  const filterResultsByCategory = (category) => {
    return post.filter((onepost) => {
      return onepost.category === category;
    });
  };
  return (
    <View style={{ flex: 1 }}>
      {/* header Date and title */}
      <LinearGradient
        colors={["#353540", "#353540", "#1E1E24"]}
        style={{ width: "100%", height: "100%" }}
      >
        <SafeAreaView style={styles.container}>
          <ScrollView style={styles.scrollView}>
            <Header headerTitle="TODAY'S ARTICLES" />
            {/* haeder Categories */}
            <Categories />
            {/* show the data in a flatlist */}
            <ArticleList data={data} navigation={navigation} />
            {/* show the categories in a flatlist*/}
            <HotTopics onCategorySelect={this.setCategory} />
            {/* show the vertical Article list */}
            <ArticleListVer
              post={filterResultsByCategory(this.state.category)}
            />
          </ScrollView>
        </SafeAreaView>
      </LinearGradient>
    </View>
  );
}
MainScreen.navigationOptions = () => {
  return {
    headerShown: false,
  };
};
const styles = StyleSheet.create({});
export default MainScreen;

【问题讨论】:

  • 为什么onpress热点有导航?
  • 我只是在尝试一些东西,我想用过滤后的数据将用户发送到另一个屏幕会容易得多,但是在主屏幕上进行更改对用户更友好
  • 是的,你可以有一个简单的回调函数作为一个道具来做

标签: javascript reactjs react-native


【解决方案1】:

处理此问题的最简单方法是使用回调函数来设置 HotTopics 组件的状态,如下所示

const [category, setCategory] = useState();

在渲染中

  <HotTopics onCategorySelect={setCategory} />
  <ArticleListVer post={filterResultsByCategory(category)} />

对于热门话题的onclick你可以做

onPress={() =>
            this.props.onCategorySelect(item.category)
          }

通过这样做,您将使用新类别重新呈现父级。对于重置,您需要一个按钮将状态重置为空,以便显示所有项目。

【讨论】:

  • 在渲染部分将用于不同的屏幕(主屏幕),所以这可能会给我一个未定义的错误吧?
  • 你给的状态、过滤功能和渲染应该放在主屏幕上
  • 如果你愿意,你可以用父屏幕更新问题,然后我可以给你完整的代码:)
  • 感谢您的帮助,我刚刚用父屏幕更新了我的主要问题
  • 应该更改为 因为您正在使用基于钩子的实现
猜你喜欢
  • 1970-01-01
  • 2021-06-12
  • 1970-01-01
  • 2021-02-08
  • 1970-01-01
  • 1970-01-01
  • 2022-11-17
  • 2020-04-28
  • 1970-01-01
相关资源
最近更新 更多