如何通过React bootstrap的Dropdown组件对ReactJs中的产品进行过滤和排序

如何解决如何通过React bootstrap的Dropdown组件对ReactJs中的产品进行过滤和排序

我正在为用户的UI中的产品列表创建过滤器功能。但是我有一个问题,我不知道并且从来没有尝试过此功能,所以我真的很难解决它。我只剩下1天的时间了,所以我很困惑

这是我的Dropdown组件

import React from "react";
import { Dropdown as BootstrapDropdown } from "react-bootstrap";
import PropTypes from "prop-types";
import "../Dropdown/index.css";

const Dropdown = ({ items }) => {
  return (
    <BootstrapDropdown className="sort-dropdown">
      <BootstrapDropdown.Toggle
        className="sort-dropdown-toggle"
        variant="success"
        id="dropdown"
      >
        <span className="toggle-text">Selection</span>
      </BootstrapDropdown.Toggle>

      <BootstrapDropdown.Menu className="sort-dropdown-menu">
        {items.map((name,index) => (
          <BootstrapDropdown.Item
            className="sort-dropdown-item"
            key={index}
            href={`#/action-${index}`}
          >
            {name}
          </BootstrapDropdown.Item>
        ))}
      </BootstrapDropdown.Menu>
    </BootstrapDropdown>
  );
};

Dropdown.propTypes = {
  items: PropTypes.array,};

Dropdown.defaultProps = {
  items: [],};

export default Dropdown;

这是我的页面,是我获得Dropdown组件的地方

import React from "react";
import { Row } from "react-bootstrap";
import Group from "../../../components/Group/index";
import Dropdown from "../../../components/Dropdown/index";
import "../GroupBar/index.css";

const GroupBar = () => {
  return (
    <Row className="group-bar">
      <Group
        title="Product group"
        element={<Dropdown items={["Milk Tea","Juice"]} />}
      />
      <Group
        title="Sort by price"
        element={<Dropdown items={["Low to hight","Hight to low"]} />}
      />
    </Row>
  );
}

export default GroupBar;

我想通过下拉列表items对产品页面进行过滤(按类别)和排序(按价格)。当我选择该项目时,产品将根据我选择的项目进行过滤。

这是我的产品列表页面

import React,{ useEffect } from "react";
import { Container,Row,Col } from "react-bootstrap";
import ProductItem from "../../../components/ProductItem/index";
import Loading from "../../../components/Loading";
import PropTypes from "prop-types";
import "../../../common/index.css";
import "../ProductList/index.css";

const ProductList = ({ products,loading,fetchProductRequest }) => {
  useEffect(() => {
    fetchProductRequest();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  },[]);

  if (loading) {
    return (
      <Container>
        <Row>
          <Col>
            <Loading />
          </Col>
        </Row>
      </Container>
    );
  }
  return (
    <Container>
      <Row>
        {!!products && products.length > 0 ? (
          products.map((product,index) => {
            return (
              <ProductItem
                key={index}
                image={product.image}
                name={product.name}
                price={product.price}
              />
            );
          })
        ) : (
            <h4 className="center-title">Product list is empty!</h4>
          )}
      </Row>
    </Container>
  );
};

export default ProductList;

这是该页面,

enter image description here

产品列表和过滤器/排序位于相同的文件夹中,但位于不同的文件中。像这样

enter image description here

组栏包含过滤器/排序。我得到了redux,saga的所有值

包含所有内容的主页在这里

import React from "react";
import { Container } from "react-bootstrap";
import GroupBar from "./GroupBar";
import ProductContainer from "../../containers/ProductContainer";
import Carousel from "../../components/Carousels";
import "../Product/index.css";

const Product = () => {
  return (
    <Container fluid className="p-0">
      <Carousel />
      <Container>
        <GroupBar />
        <ProductContainer />
      </Container>
    </Container>
  );
};

export default Product;

当类似这样的文件时,如何过滤与列表产品相关的内容。

Please anyone help me with this my problem,I just have one day to finish that function,我已经在互联网上进行了研究,但这并不能使我了解更多,因为它与我的代码有很大不同,因此我无法将其应用于我的代码。

我真的非常需要您的支持和帮助,并且更好。不仅帮助我了解了像我这样的其他人,他们在尝试之前也没有尝试过它,也看到了代码也很容易理解。

我总是欢迎您的所有评论。那是我的荣幸。非常感谢。

解决方法

您将需要您的组件来跟踪某些状态。您可以阅读有关herehere的操作方法。

一旦了解了状态的概念,就需要跟踪选择列表中的哪个项目。因此,例如,您需要保留一个状态变量,以跟踪是选择了“牛奶茶”还是“果汁”。

然后,一旦处于该状态,就可以使用filter列表上的sortitems显示项目。

我个人建议使用类组件而不是函数组件,但这是使用函数组件的最小工作示例:

import React,{ useState } from 'react';
import { Dropdown as BootstrapDropdown } from 'react-bootstrap';
import './App.css';

const Dropdown = (props) => {
    return (
        <BootstrapDropdown>
            <BootstrapDropdown.Toggle variant='success' id='dropdown'>
                <span>Selection</span>
            </BootstrapDropdown.Toggle>

            <BootstrapDropdown.Menu>
                {props.items.map((name,index) => (
                    <BootstrapDropdown.Item
                        key={index}
                        onClick={(event) => {
                            console.log(event.target.text);
                            props.setSelected(event.target.text);
                        }}
                        value={name}
                    >
                        {name}
                    </BootstrapDropdown.Item>
                ))}
            </BootstrapDropdown.Menu>
        </BootstrapDropdown>
    );
};

function App() {
    const [typeFilter,setTypeFilter] = useState('');

    const allItems = [
        { name: 'Coffee Milk Tea',type: 'Tea' },{ name: 'Earl Gray Milk Tea',{ name: 'Orange Juice',type: 'Juice' },{ name: 'Wheatgrass Juice',];

    const itemsToShow = allItems
        .filter((item) => {
            if (typeFilter) {
                return item.type === typeFilter;
            }
            return true;
        })
        .map((item,i) => {
            return <li key={i}>{item.name}</li>;
        });

    return (
        <div>
            <Dropdown items={['Tea','Juice']} setSelected={setTypeFilter} />
            <ol>{itemsToShow}</ol>
        </div>
    );
}

export default App;

请注意,App组件存储了状态,并将其状态设置器传递给Dropdown组件。 Dropdown使设置器进入其props,并在单击选项时使用它来设置App的状态。 App然后使用其状态来确定要显示的项目(使用items.filter)。

这是Lifting state up的示例。通常,我们会考虑跟踪选择哪个项目作为下拉菜单的工作。但是,由于我们需要在另一个组件中访问该状态,因此我们必须将该状态“提升”到树中更高的位置。在这个小例子中,存储状态的是App。通常,如果树看起来像这样:

  • A
    • B
      • C
      • D
    • E
      • F
        • G
    • H

,并且要在G和D之间共享状态,您需要将该状态放入A内,因为A是G和D的最接近父级。如果要在C和D之间共享状态,则需要将该状态放入B,因为B是C和D的父代。

关于下面的评论,您可能希望保持在Product组件内选择下拉菜单中的内容的状态。然后,您需要将状态设置器一直沿props链传递到Dropdown组件中,该组件可以调用该设置器并更新状态。

很抱歉得知您的日程安排很紧。希望这个答案对您有用。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-