我正在研究基于类别的过滤器。对于单个类别,它可以工作,但是如何为多个类别选择实现它?
示例:如果用户单击“服装”和“运动”,则他应该能够看到两个类别的列表。
Redux state:
categories
>0 :{id:999 , name:'All', slug:'all'}
>1 :{id:2 , name:'clothing', slug:'clothing'}
>2 :{id:1 , name:'sport', slug:'sport'}
class ListFilter extends React.Component {
changeFilter = (category) => {
this.props.changeFilter(category, this.props.text);
gaEvent("Home - ListFilter", category, this.props.text);
};
clearFilters = () => {
this.props.changeFilter('all', '');
gaEvent("Home - ListFilter", "Reset");
};
render() {
return (
<>
<div className={classNames({
"search_list__filters": true,
"search_list--show": this.props.search
})}>
{this.props.categories.map((category, index) => {
return (
<Form.Group key={index} className="search_filters" >
<Form.Check onClick={(event)=>(event.target.checked!==true)?this.clearFilters():this.changeFilter(category.slug)} custom inline label={category.name} className='search_list__btn' type='checkbox' id={category.name} />
</Form.Group>
)
})}
<Row className="search_list_btn search_list__clear ">
<Col className="clear_wrapper">
{this.props.filters &&
<button className="clear_btn" onClick={this.clearFilters} >
Clear all filters
</button>
}
</Col>
</Row>
</div>
</>
);
}
}
const mapStateToProps = state => {
return state.Store
}
;
const mapDispatchToProps = dispatch => ({
changeFilter: (category, text) => dispatch(changeFilter(category, text))
});
export default connect(mapStateToProps, mapDispatchToProps)(ListFilter);
答案 0 :(得分:0)
当前,您正在分派单个类别的changeFilter
事件。您可以将过滤器存储在State
中,并使用类别数组调度事件。请参阅CodeSandbox,以使用多个类别过滤器。
class ListFilter extends React.Component {
constructor(props) {
super(props);
this.state = {
filters: []
};
}
changeFilter = category => {
const { filters } = this.state;
const updatedFilter = [...filters, category];
this.setState({
filters: updatedFilter
});
this.props.changeFilter(updatedFilter, "testText");
};
render() {
console.log(this.state.filters);
return (
<div className="App">
{categories.map((category, index) => {
return (
<Form.Group key={index} className="search_filters">
<Form.Check
onClick={event =>
event.target.checked !== true
? this.clearFilters()
: this.changeFilter(category.slug)
}
custom
inline
label={category.name}
className="search_list__btn"
type="checkbox"
id={category.name}
/>
</Form.Group>
);
})}
</div>
);
}
}