Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
573 views
in Technique[技术] by (71.8m points)

javascript - 当我仅更改状态而不使用任何CSS时,为什么我的React应用程序菜单会打开?(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.(我的页眉组件中有一个按钮。)

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(我的密码箱)   ask by Elijah Lee translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.(第二次渲染时,更新状态后将其推送到上下文,然后将其作为prop(!)传递给<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。)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...