我有2个按钮,当单击它们时,应按novelty
或进行过滤,offer
以便能够在单击新颖性时对其进行过滤,但是我无法做到这一点,因此,如果同时单击则将按novelty
和进行过滤offer
我该如何做,以便在同时点击新颖性和要约时将其全部过滤掉?
https://www.webpackbin.com/bins/-KpVGNEN7ZuKAFODxuER
import React from 'react'
export default class extends React.Component {
constructor() {
super()
this.state = {
products: [
{ id: 1, novelty: true, offer: false, name: 'test1' },
{ id: 2, novelty: true, offer: true, name: 'test2' },
{ id: 3, novelty: false, offer: true, name: 'test3' }
],
display: 'all',
filters: [
{novelty:'true'},
{offer: 'true'}
]
}
}
setCategory (category) {
this.setState({
display: category
});
}
render() {
return(
<div>
<button onClick={()=>this.setCategory(true)}>Akce</button>
<button onClick={()=>this.setCategory(true)}>Offer</button>
{
this.state.products.filter( product =>
products.offer === this.state.display ||
this.state.display==='all')
.map(product =>
<div>{product.name}</div>
)
}
</div>
)
}
}
这是我想出的最终版本:
import React from 'react'
export default class extends React.Component {
constructor() {
super()
this.state = {
products: [
{ id: 1, novelty: true, offer: false, name: 'test1' },
{ id: 2, novelty: true, offer: true, name: 'test2' },
{ id: 3, novelty: false, offer: true, name: 'test3' }
],
filters: {
novelty: true,
offer: true
}
}
}
setCategory (category) {
this.setState((state) => ({
filters: Object.assign({}, state.filters, { [category]: !state.filters[category] })
}));
}
render() {
console.log(this.state.filters)
return(
<div>
<button onClick={()=>this.setCategory('novelty')}>Akce</button>
<button onClick={()=>this.setCategory('offer')}>Offer</button>
{ this.state.products
.filter(product => product.novelty === this.state.filters.novelty || product.offer === this.state.filters.offer)
.map(product =>
<div key={product.id}>{product.name}</div>
)}
</div>
)
}
}
https://www.webpackbin.com/bins/-KpVHqfkjeraq6pGvHij
一些东西:
true
而不是'true'
)。display: 'all'
您的用例不需要。您可以根据需要从过滤器计算该值。setCategory
接收category
要设置为参数的对象。setCategory
为setFilter
另外,我正在使用的异步版本setState
。这使您可以上交功能。
this.setState((state) => ({
filters: Object.assign({}, state.filters, { [category]: !state.filters[category] })
}));
在这里,我Object.assign
用来创建一个新的对象。我用他来填充state.filters
,最后我更新了想要的过滤器。category
将会是novelty
或,offer
并且感谢我使用的简写版本[category]
。
最后,我还更新filter
功能来检查product.novelty
对filter.novelty
或product.offer
与filter.offer
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句