[英]Why does my React app menu open when I am only changing the state and am not using any CSS?
I have a button in my Header component.我的 Header 组件中有一个按钮。 When it is clicked, it calls a toggleNav function stored in my context.js.当它被点击时,它会调用一个存储在我的 context.js 中的 toggleNav 函数。 This function changes the state of isNavOpen from false to true.此函数将 isNavOpen 的状态从 false 更改为 true。 The navgiation then opens.导航随即打开。 There is no CSS in my project that should allow this behavior.我的项目中没有 CSS 应该允许这种行为。 I also don't see any JS code that should allow this behavior either.我也没有看到任何应该允许这种行为的 JS 代码。 Could someone tell me what code allows my navigation to open and close?有人能告诉我什么代码允许我的导航打开和关闭吗?
My codesandbox我的密码箱
This is down to the basic way that React works, when you change the state
of a component, it re-renders itself with the new values you've set into state
.这取决于 React 的基本工作方式,当您更改组件的state
时,它会使用您在state
设置的新值重新呈现自身。
Specifically it's this bit of Header.js:具体来说就是 Header.js 的这一点:
{context.state.isNavOpen && (
<div className="js-nav nav">
...
When the component renders the first time, context.state.isNavOpen
is false, and false && anything
is still false, so javascript ignores the code after the &&
.当组件第一次渲染时, context.state.isNavOpen
为false, false && anything
仍然是false,所以javascript 忽略&&
后面的代码。 That means it skips over the menu code.这意味着它会跳过菜单代码。
The second time it renders, after you update the state which is pushed to context and then passed to <Header>
as a prop (!), the component re-renders with your menu code.第二次渲染时,在您更新推送到上下文然后作为道具 (!) 传递给<Header>
的状态后,组件会使用您的菜单代码重新渲染。
If you use your browser's dev tools to inspect the DOM before and after you click the button, you'll find that the menu isn't hidden and shown, but rather when you don't see it, it's gone from the DOM altogether.如果您在单击按钮之前和之后使用浏览器的开发工具检查 DOM,您会发现菜单没有隐藏和显示,而是当您看不到它时,它完全从 DOM 中消失了。
It's react feature whenever state changes component re-renders每当状态改变组件重新渲染时,它的反应功能
same thing happening here同样的事情发生在这里
{context.state.isNavOpen && (
isNavOpen
is toggling (true to false), (false to true) isNavOpen
正在切换(真到假),(假到真)
for example - you can check it simply例如 - 你可以简单地检查它
class Toggle extends React.Component {
state = {
visibility: false
}
toggleVisibility=()=>{
this.setState(prev=>({visibility:!prev.visibility}))
}
render() {
const {visibility} = this.state;
return (
<div>
<button onClick={this.toggleVisibility}>Click Me</button>
<h3>{visibility?'Welcome':''}</h3>
</div>
);
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.