gpt4 book ai didi

reactjs - 当我使用 Lifting State Up 时 useState(false) 不起作用

转载 作者:行者123 更新时间:2023-12-04 07:36:54 25 4
gpt4 key购买 nike

第一个代码是一个共同的祖先组件,我将 props 传递给了 Layout 组件。结果总是正确的。但我希望它默认为 false。我想在使用 handleOnClick 时将其更改为 true我做错了什么??
如果有不清楚的解释,请告诉我。

import React, { useState } from "react";
import "./App.css";
import Sidebar from "./Components/Sidebar";
import Layout from "./pages/LayOut/Layout";
import ChartType from "./pages/ChartType/ChartType";
import Home from "./pages/Home";
import Datasetting from "./pages/Datasetting";
import View from "./pages/View";
import { Switch, Route } from "react-router-dom";
function App() {
const [showPanel, setShowPanel] = useState(false); // this one
const [showPanel1, setShowPanel1] = useState(false);

return (
<div className="App">
<Sidebar />
<Switch>
<Route path="/home" exact>
<Home />
</Route>
<Route path="/layout">
<Layout
showPanel={showPanel}
setShowPanel={setShowPanel}
showPanel1={showPanel1}
setShowPanel1={setShowPanel1}
/>



import Panel from "./Panel";
import PanelTwo from "./PanelTwo";
import styled from "styled-components";
export default function Layout({
showPanel,
setShowPanel,
showPanel1,
setShowPanel1,
}) {
const handleOnClick = () => {
setShowPanel(true);
setShowPanel(false);
};
const handleOnClick1 = () => {
setShowPanel1(true);
setShowPanel(false);
};

return (
<div>
<Main>
<div onClick={handleOnClick}>
<h1>Panel (1+3)</h1>
</div>

问题解决了 !非常感谢你们花时间回答!!
我希望你们有美好的一天!!

最佳答案

import React, { useState } from "react";
import "./App.css";
import Sidebar from "./Components/Sidebar";
import Layout from "./pages/LayOut/Layout";
import ChartType from "./pages/ChartType/ChartType";
import Home from "./pages/Home";
import Datasetting from "./pages/Datasetting";
import View from "./pages/View";
import { Switch, Route } from "react-router-dom";
function App() {
const [showPanel, setShowPanel] = useState(false); // this one
const [showPanel1, setShowPanel1] = useState(false);

const handleOnClick = () => {
setShowPanel(!showPanel);
setShowPanel1(!showPanel1);
}; // dont need 2nd function with setting showPanel(1) with the bang operator, takes opposite of current value


return (
<div className="App">
<Sidebar />
<Switch>
<Route path="/home" exact>
<Home />
</Route>
<Route path="/layout">
<Layout
showPanel={showPanel}
handleOnClick={handleOnClick}
showPanel1={showPanel1}
/>

import Panel from "./Panel";
import PanelTwo from "./PanelTwo";
import styled from "styled-components";
export default function Layout({
showPanel,
showPanel1,
handleOnClick
}) {

return (
<div>
<Main>
<div onClick={handleOnClick}>
<h1>Panel (1+3)</h1>
</div>

关于reactjs - 当我使用 Lifting State Up 时 useState(false) 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67697539/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com