第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

React - 如何從另一個組件更改組件內(nèi)的狀態(tài)?

React - 如何從另一個組件更改組件內(nèi)的狀態(tài)?

素胚勾勒不出你 2023-09-28 17:11:01
這就是我想做的;我在 App.js 中有幾個組件,包括導航欄。目前,我在 App.js 中有一些代碼,這些代碼在單擊按鈕時隱藏了 App.js 中的多個組件,并同時顯示不同的視圖。我想做的是將按鈕移動到導航欄,但仍然能夠在 App.js 中切換視圖。我應該如何在導航欄和 App.js 之間共享狀態(tài)。這是我的導航欄代碼;export default class NavBar extends React.Component { constructor(props) {  super(props); }render() { let style = this.props.styleOptions; return (   <nav    class="navbar fixed-top"    style={{      backgroundColor: style.navBackground,      borderColor: style.navBorderColor,    }}  >    <div      className="nav-brand-conainter"      style={{ backgroundColor: style.navLogoBackground }}    >      <a class="navbar-brand" href="#">        <img src={style.logoUrl} alt="" />      </a>    </div>    <div className="navbar-contents">      <SearchBar        onSearchTermChanged={this.props.onSearchTermChanged}        style={{ color: style.secondaryTextColor }}      ></SearchBar>    </div>    <UserBox></UserBox>  </nav>);}}我希望能夠從 NavBar 按鈕隱藏 App.js 中的組件,謝謝。
查看完整描述

2 回答

?
梵蒂岡之花

TA貢獻1900條經(jīng)驗 獲得超5個贊

根據(jù)您的代碼,您似乎已經(jīng)知道該怎么做。就舉onSearchTermChanged個例子吧。


在您的NavigationBar組件中這樣做:


    ...

    <div>

      <button onClick={this.props.onToggle}>Toggle</button>

    </div>

    ...

如果您的導航欄需要了解狀態(tài),您可以考慮添加額外的處理程序:


  constructor(props) {

    ...

    this.handleToggle = this.handleToggle.bind(this);

  }


  handleToggle() {

    this.setState({ toggled: !this.state.toggled });

    this.props.onToggle();

  }


  render() {

    ...

    <div>

      <button onClick={this.handleToggle}>Toggle</button>

    </div>

    ...

  }

在您的應用程序組件中:


    ...

    <NavBar

      onSearchTermChanged={this.searchReturn}

      onToggle={this.toggleMainView} // <----

      styleOptions={this.state.style}

      showMainView={this.state.showMainView}

      featuresVisible={this.state.featuresVisible}

    ></NavBar>

    ...


查看完整回答
反對 回復 2023-09-28
?
汪汪一只貓

TA貢獻1898條經(jīng)驗 獲得超8個贊

要共享一個組件中的狀態(tài),您可以使用 HOC 或更高階組件來實現(xiàn)這一點。

查看完整回答
反對 回復 2023-09-28
  • 2 回答
  • 0 關(guān)注
  • 154 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學習伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號