reactjs 如何在React中实现此下拉筛选器中的“全部”

42fyovps  于 2022-12-03  发布在  React
关注(0)|答案(1)|浏览(177)

我想添加这个“全部”功能,这样我就可以一次显示所有的费用。现在我只能看到按年度筛选的费用。

import React from 'react';

import './ExpensesFilter.css';

const ExpensesFilter = (props) => {
    const dropdownChangeHandler = (event) => {
        props.onChangeFilter(event.target.value);
    };
    
    return (
        <div className="expenses-filter">
            <div className="expenses-filter__control">
                <label>Filter by year</label>
                <select value={props.selected} onChange={dropdownChangeHandler}>
                    <option value='2022'>2022</option>
                    <option value='2021'>2021</option>
                    <option value='2020'>2020</option>
                    <option value='2019'>2019</option>
                    <option value='All'>All</option>
                </select>
            </div>
        </div>
    );
};

export default ExpensesFilter;

这是应用筛选的主要Expenses.js组件

function Expenses(props) {
  const [filteredYear,setFilteredYear] = useState('2020');
  
  const filterChangeHandler = selectedYear => {
    setFilteredYear(selectedYear);
  };

  const filteredExpenses = props.items.filter(expense => {
    return expense.date.getFullYear().toString() === filteredYear;
  });

第二部分

return (
    <div>
    <Card className='expenses'>
        <ExpensesFilter selected={filteredYear} onChangeFilter={filterChangeHandler}/>
    <ExpensesChart expenses={filteredExpenses}/>
    <ExpensesList items={filteredExpenses}/>
    </Card>
    </div>);
  };
export default Expenses;
laik7k3q

laik7k3q1#

您已经得到了所需的一切。您设置的方式只需稍作改动即可。当选定的筛选器为"All"时,您不希望筛选费用:

const filteredExpenses =
  filteredYear === "All"
    ? props.items
    : props.items.filter((expense) => {
        return expense.date.getFullYear().toString() === filteredYear;
      });

相关问题