我正在尝试在Next JS中显示和隐藏按钮上的div。
这篇文章对我有很大帮助:Next.js toggle display of a div tag
在我的案例中,我使用useState来使用此解决方案,并且效果很好。区别在于我有很多按钮,并且每个按钮都假定显示不同的div并隐藏活动的div。
这是我要实现的目标https://codepen.io/CthuKi/pen/YqZvRv
export default function Header(){
const [showMe, setShowMe] = useState(false);
function toggle(){
setShowMe(!showMe);
}
return (
<>
<button onClick={toggle}>Button 1</button>
<button onClick={toggle}>Button 2</button>
<button onClick={toggle}>Button 3</button>
<div>
<div style={{display: showMe?"block":"none"}}>
Show this div on button 1 and hide other active
</div>
<div style={{display: showMe?"block":"none"}}>
Show on button 2 and hide other active
</div>
<div style={{display: showMe?"block":"none" }}>
Show on button 3 and hide other active
</div>
</div>
</>
);
}
我将不胜感激
一种解决方案是具有多个toggle
功能来切换多个div
。但是有一种更好的方法,只创建一个状态变量showAll
和一个函数toggleAll
以显示所有内容。
要切换一个按钮以显示特定的内容,请创建要显示的数据数组,然后更改索引以显示该数组中的当前数据。
例如,请参见codesandbox进行演示
import React, { useState } from "react";
export default () => {
const [data, setData] = useState(["hello", "hi there", "holla"]);
const [showAll, setShowAll] = useState(false);
const [currentIdx, setCurrentIdx] = useState(0);
const [showCurrent, setShowCurrent] = useState(false);
const toggleAll = () => {
setShowAll(val => !val);
setShowCurrent(false);
};
const toggleCurrent = () => {
if (!showCurrent) {
setShowCurrent(true);
setShowAll(false);
return;
}
};
const setCurrent = index => {
setCurrentIdx(index);
toggleCurrent();
};
return (
<div>
<div>
<button onClick={toggleAll}>{showAll ? "Hide All" : "Show All"}</button>
<button onClick={() => setCurrent(0)}>First</button>
<button onClick={() => setCurrent(1)}>Second</button>
<button onClick={() => setCurrent(2)}>Third</button>
</div>
<div>
{showAll && data.map((el, i) => <p key={`content-${i}`}>{el}</p>)}
</div>
{showCurrent ? <div>{data[currentIdx]}</div> : null}
</div>
);
};