如何切换动态div下拉列表NEXT.JS



我正在使用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处于打开状态,其他索引处于关闭状态。单击索引0时,它不会关闭。单击索引1,它将打开,索引0将关闭。

我希望输出为,最初所有的下拉列表都应该是打开的。单击每个div后,它应该被关闭,单击它应该被打开。如何修改我的代码来实现这一点。

您需要检查单击的项目是否已经打开,您可以在其setter函数的第一个参数中获得setState的当前值:

// 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"}}>
...

最新更新