根据react中的if else语句显示/隐藏组件
有一些代码看起来像这样,
const Movies = () => {
const [show, setShow] = useState(false);
const [show1, setShow1] = useState(false);
const onClick = () => setShow(!show);
const onClick1 = () => setShow1(!show1);
return (
<div className="movie">
<Header />
<h2>Discover a new movie!</h2>
<div className="showBtns">
<button onClick={onClick} className="right">Search <FaSearch /></button>
<button onClick={onClick1}>Discover <FaSearch /></button>
</div>
{show1 ? <DropDown /> : null }
{show ? <MovieSearch /> : null }
<Nav />
</div>
);
};
我现在
如果我单击任一按钮,它将显示相应的组件,但如果单击两个按钮,它们都会显示。我想编写一个 if else 语句来检查一个是否显示,然后另一个不应显示。
我尝试了几种不同的方法,但似乎无法使其发挥作用。
任何有关更好的方法或如何使其发挥作用的反馈将不胜感激。
if(show === true){
setShow1(false)
} else if(show1 === true) {
setShow(false)
}
这会产生“太多重新渲染”的错误。 React 限制渲染数量以防止无限循环。
I have some code that looks like this
const Movies = () => {
const [show, setShow] = useState(false);
const [show1, setShow1] = useState(false);
const onClick = () => setShow(!show);
const onClick1 = () => setShow1(!show1);
return (
<div className="movie">
<Header />
<h2>Discover a new movie!</h2>
<div className="showBtns">
<button onClick={onClick} className="right">Search <FaSearch /></button>
<button onClick={onClick1}>Discover <FaSearch /></button>
</div>
{show1 ? <DropDown /> : null }
{show ? <MovieSearch /> : null }
<Nav />
</div>
);
};
as of right now if I click on the button for either one it will show the corresponding component but if both are clicked they both show up.
I'd like to write an if else statement to check if one is showing then the other should not be shown.
I've tried a few different things and can't seem to get it to work.
any feedback on a better way to do this or how to get it to work would be appreciated.
if(show === true){
setShow1(false)
} else if(show1 === true) {
setShow(false)
}
this gives an error of Too many re-renders. React limits the number of renders to prevent an infinite loop.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以在单击事件中处理这些按钮的隐藏/显示逻辑,因为这是状态更改的地方。
示例:
https://codesandbox.io/s/wild-wild-wild-wild-wild-wilt-wild-water-wild-water-wild-water -f5nzor?file =/src/app.js
You can handle the hiding/showing logic for these button in the click events because that is where the state changes.
Example:
https://codesandbox.io/s/wild-water-f5nzor?file=/src/App.js
您可以像这样修改 onClick 函数:
const onClick = () =>; setShow((prevState) => !show1 && !prevState); const onClick1 = () =>; setShow1((prevState) => !show && !prevState);
You can modify your onClick functions like this:
const onClick = () => setShow((prevState) => !show1 && !prevState); const onClick1 = () => setShow1((prevState) => !show && !prevState);