反应复选框过滤器数据

时间:2019-05-04 21:47:54

标签: reactjs

我正在尝试在React中进行一些基本的复选框过滤,但是遇到了麻烦。我将默认状态设置如下:

const [state, setState] = React.useState({
    items: [
      {title: 'item 1', type: 'beginner'},
      {title: 'item 2', type: 'beginner'},
      {title: 'item 3', type: 'advanced'}
    ],
    setItems: [],
    selectedFilters: []
  })

并具有handleFilterChange函数,如果我单击复选框,它将获得偶数和值。根据检查的内容筛选数据的最佳方法是什么?因此,如果同时检查了初学者和高级用户-它会显示所有内容,就像未检查任何内容一样。如果选中beginner,则应该只显示初学者数据。

这是所有代码:

import React from 'react'
import Layout from '../components/Layout'
import Card from '../components/Card'
import styled from 'styled-components'

const FilterWrapper = styled.div`
  margin: 1rem 0;
`

const Wrapper = styled.div`
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
  grid-gap: 15px;
`

const Filters = () => {
  const [state, setState] = React.useState({
    items: [
      {title: 'item 1', type: 'beginner'},
      {title: 'item 2', type: 'beginner'},
      {title: 'item 3', type: 'advanced'}
    ],
    setItems: [],
    selectedFilters: []
  })

  const handleFilterChange = (e) => {

    let filters = state.selectedFilters
    let newFilters = []

    // e.target.checked ? newFilters.push(e.target.value) : newFilters = filters.filter(item => item !== e.target.value)
    newFilters.push(e.target.value)

    setState({
      ...state,
      selectedFilters: newFilters
    })


  }

  React.useEffect(() => {
    setState({
      ...state,
      setItems: state.items
    })
  }, [])



  return (
    <Layout>
      <p>Filters</p>
      <FilterWrapper>
        <label>
          <input type="checkbox" value='beginner' onChange={handleFilterChange}/>
          <span>Beginner</span>
        </label>

        <label>
          <input type="checkbox" value='advanced' onChange={handleFilterChange}/>
          <span>Advanced</span>
        </label>

      </FilterWrapper>
      <Wrapper>
        {state.setItems && state.setItems.map((item, i) => {
          return <Card key={i} />
        })}
      </Wrapper>
    </Layout>
  )
}

export default Filters

0 个答案:

没有答案