【问题标题】:How to use State value outside the function in React JS如何在 React JS 中的函数外使用 State 值
【发布时间】: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中声明toggleStatesetToggleState,然后通过props传递给Header。
  • 定义并保持 App 中的状态,并将其传递给任何需要它的组件。此外,您的导入语句 'toggleState from “components/Header”' 实际上导入了名称为 toggleState 的 Header 组件。
  • @WilsonLiao 能否分享一下代码,如何通过 props 将它们传递给 header?/

标签: javascript html css reactjs


【解决方案1】:

你需要在App中声明toggleState、setToggleState,然后通过props传递给Header。

//in App
const [toggleState, setToggleState] = useState(true);

render() {
  return <Header toggleState={toggleState} setToggleState={setToggleState} />
}


//in Header
function Header(props) {
// get the value
const { toggleState } = props

//call the function
props.setToggleState(toggleState)

...

【讨论】:

  • const { toggleState } = this.props ,它是一个功能组件,所以我认为是“这个”。不管用。那么我应该写什么而不是'this.props.setToggleState(toggleState)'
  • 怎么样?我刚刚修改了sn-p。
猜你喜欢
  • 2019-09-07
  • 1970-01-01
  • 1970-01-01
  • 2020-10-24
  • 2021-10-15
  • 1970-01-01
  • 2023-03-10
  • 2016-12-07
  • 2021-11-30
相关资源
最近更新 更多