我正在使用NEXT.JS和REDUX建立电子商务商店。在产品列表页面中,我有包含大小,颜色等的过滤器部分。单击标题时,内容应切换。我尝试使用下面的代码,但无法正常工作。
const [showMe, setShowMe] = useState(0);
function toggle(index) {
setShowMe(index);
}
<div className="other">
<h6>Refine</h6>
<hr/>
{products.filter.map((item, index) => (
<div key={index}>
<div className="single">
<div className="title" onClick={() => toggle(index)}>
<p className="float-left">{item.title}</p>
<p className="float-right"><FontAwesomeIcon icon={showMe === index ? faChevronUp : faChevronDown}/></p>
</div>
<ul style={{display: showMe === index ? "block" : "none"}}>
{item.items.map((single, index1) => (
<li key={index1}>
<label><input type="checkbox" name="checkbox" value="value"/> {single.items_value}</label>
</li>
))}
</ul>
</div>
<hr/>
</div>
))}
</div>
最初索引0是打开的,其他索引是关闭的。Onclick索引0不会关闭。Onclick索引1打开,索引0关闭。
我想要输出,因为最初所有下拉列表都应该打开。单击每个div后,应将其关闭,然后单击它,则应将其打开。如何更改我的代码以实现此目的。
您需要检查单击的项目是否已打开,可以setState
在其setter
功能的第一个参数中获取a的当前值:
// use an empty array for intial value:
const [showMe, setShowMe] = useState([]);
// after you got `products`:
setShowMe(Array(products.filter.length).fill(0).map((_, index) => index))
function toggle(index) {
setShowMe(currentShowMe => currentShowMe.includes(index)
? currentShowMe.filter(i => i !== index)
: [...currentShowMe, index]);
}
...
<ul style={{display: showMe.includes(index) ? "block" : "none"}}>
...
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句