这里是新的 React 开发人员,正在寻找可以同时切换两件事的 react(hooks) 开关。我的问题:当用户单击“单击此处显示第二个 Div 内容”时,内容应更改为“
这里需要什么样的改进?
答案 0 :(得分:1)
这对我有用:
import React, { useState } from "react";
function App() {
const [openMenu, setOpenMenu] = useState("first");
const toggleMenu = () => {
if (openMenu === "first") {
setOpenMenu("second");
} else {
setOpenMenu("first");
}
};
return (
<div className="App">
<button
onClick={toggleMenu}
>{`Click here to swap content`}</button>
{openMenu === "first" ? (
<div>
<p>First Div content</p>
</div>
) : (
<div>
<p>Second Div content</p>
</div>
)}
</div>
);
}
export default App;
答案 1 :(得分:0)
您做对了,但是当 null
为 false 时不应返回 openMenu
,您应该呈现其他内容。
import React, { useState } from "react";
function App() {
const [openMenu, setOpenMenu] = useState(true);
const toggleMenu = () => {
setOpenMenu(!openMenu);
};
return (
<div className="App">
{openMenu ? (
<div>
<button
onClick={toggleMenu}
>{`Click here to show second Div content`}</button>
<p>First Div content</p>
</div>
) : (
<div>
<button
onClick={toggleMenu}
>{`Click here to show first Div content`}</button>
<p>second Div content</p>
</div>
)}
</div>
);
}
export default App;
答案 2 :(得分:-1)
你可以这样做;
const toggleMenu = () => {
setOpenMenu(!openMenu);
if(openMenu){
setOpenMenu2("first");
} else {
setOpenMenu2('second')
}
};
return (
<div className="App">
<button
onClick={toggleMenu}
>{`Click here to show ${openMenu2} Div content`}</button>
{openMenu ? (
<div>
<p>First Div content</p>
</div>
) : <div><p> Second Div content </p> </div>}
</div>
);
}