tom*_*son 6 javascript reactjs
我有两个按钮,当点击时应该过滤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>
)
}
}
Run Code Online (Sandbox Code Playgroud)
Cyr*_*l F 10
这是我提出的最终版本:
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>
)
}
}
Run Code Online (Sandbox Code Playgroud)
https://www.webpackbin.com/bins/-KpVHqfkjeraq6pGvHij
一些东西:
true而不是'true').display: 'all'您的用例不是必需的.如果需要,您可以从过滤器中计算此值.setCategory收到category你想要设置为param的内容.setCategory为setFilter另外,我正在使用asycnhronous版本setState.这允许您提交功能.
this.setState((state) => ({
filters: Object.assign({}, state.filters, { [category]: !state.filters[category] })
}));
Run Code Online (Sandbox Code Playgroud)
这里我Object.assign用来创建一个新的Object.我填充他, state.filters最后我更新你想要的过滤器.
category将是novelty或者offer由于我正在使用速记版本[category].
总而言之,我还更新了你的filter功能,以检查product.novelty对抗filter.novelty或product.offer与filter.offer
| 归档时间: |
|
| 查看次数: |
6552 次 |
| 最近记录: |