我想在我的React应用中按类别实现过滤器。
当我检查一个类别时,它们就会起作用。
我现在无法解决的问题-仅应用了一个过滤器。因此,如果我选择1
和All
,则仅1
适用。还有另一个问题是,当我取消选中过滤器时,它们不会重置。
在这些问题上的所有帮助将不胜感激。
在第一个问题中,我假设我需要将过滤器转换为数组或对象,以便可以存储多个值?
Filters.tsx
import React from 'react'
interface stopsFilterProps {
setCurrentFilter: (stops: string | number) => void
}
const StopsFilter: React.SFC<stopsFilterProps> = ({ setCurrentFilter }: stopsFilterProps) => {
return (
<div className="stops-filters">
<ul className="stops-filter__list">
<li className="stops-filter__list-item">
<label className="stops-filter__list-label" htmlFor="all">All</label>
<input id="all" type="checkbox" onChange={() => setCurrentFilter('All')} />
</li>
<li className="stops-filter__list-item">
<label className="stops-filter__list-label" htmlFor="zero">0</label>
<input id="zero" type="checkbox" onChange={() => setCurrentFilter(0)} />
</li>
<li className="stops-filter__list-item">
<label className="stops-filter__list-label" htmlFor="one">1</label>
<input id="one" type="checkbox" onChange={() => setCurrentFilter(1)} />
</li>
<li className="stops-filter__list-item">
<label className="stops-filter__list-label" htmlFor="two">2</label>
<input id="two" type="checkbox" onChange={() => setCurrentFilter(2)} />
</li>
<li className="stops-filter__list-item">
<label className="stops-filter__list-label" htmlFor="three">3</label>
<input id="three" type="checkbox" onChange={() => setCurrentFilter(3)} />
</li>
</ul>
</div>
)
}
export default StopsFilter;
其父组件
import React from 'react';
import StopsFilter from '../../blocks/Filters/StopsFilter'
interface stopsFilterComponentProps {
setFilter: (stops: string | number) => void
}
const StopsFilterComponent: React.SFC<stopsFilterComponentProps> = ({setFilter}:stopsFilterComponentProps) => {
function setCurrentFilter (stops: string | number) {
setFilter(stops);
}
return (
<div className="container">
<StopsFilter setCurrentFilter={setCurrentFilter}></StopsFilter>
</div>
)
}
export default StopsFilterComponent;
在App.tsx中
const App: React.SFC = () => {
const [stopsFilter, setFilter] = useState<string | number>('All')
return (
<div className="App">
<div className="filters-holder">
<StopsFilterComponent setFilter={(stops: string | number) => setFilter(stops)}></StopsFilterComponent>
</div>
</div>
);
}
export default App;