【发布时间】:2020-01-21 16:27:31
【问题描述】:
我有 2 个文件,标题和应用程序,应用程序是我的父文件,标题是子文件,我在标题中设计了一个用于打开和关闭侧边栏的按钮,但我无法做到这一点。我的问题是如何将状态值从标头传递到 App 文件。 这是代码
import Header from 'components/Header';
import FirstSection from 'components/FirstSection';
import SecondSection from 'components/SecondSection';
import ThirdSection from 'components/ThirdSection';
import FourthSection from 'components/FourthSection';
import Sidebar from 'components/Sidebar';
import toggleState from 'components/Header';
function App(props) {
return (
<div className="">
<Header setToggleState={toggleState}/>
<div className="row mlr0 w-100">
<div className={`pl-0 a ${toggleState ? 'col-md-3': 'd-none'}`} id="showOnClick">
<Sidebar />
</div>
<div className="col-md-9" id="fullScreen">
<FirstSection/>
<SecondSection/>
<ThirdSection/>
<FourthSection/>
<div className="row justify-content-center">
<img src={require("./images/Aqomi_Logo_Pink_Web_Small.png")} className="pb17"/>
</div>
</div>
</div>
</div>
);
}
export default App;
App.js
import React, { useState } from "react";
import App from './../App';
export default function Header(props){
const [toggleState, setToggleState] = useState(true);
function changeClass(){
setToggleState(!toggleState);
}
return(
<div>
<li className="nav-item"><a className="navbar-brand pl-1 hm " onClick={changeClass}>
<img src={require("./../images/line.png")} height="23px" className={toggleState.className} />
</a></li>
</div>
)
}
Header.js
【问题讨论】:
-
useState(true);可能需要使用通过props传入的状态。 -
要么你必须将
toggleState移动到App.js或使用renderProps 将数据传递给Parent 或使用redux -
嗯,你需要在App中声明
toggleState,setToggleState,然后通过props传递给Header。 -
定义并保持 App 中的状态,并将其传递给任何需要它的组件。此外,您的导入语句 'toggleState from “components/Header”' 实际上导入了名称为 toggleState 的 Header 组件。
-
@WilsonLiao 能否分享一下代码,如何通过 props 将它们传递给 header?/
标签: javascript html css reactjs