簡體   English   中英

如何獲取父App.js中的navbar子組件state?

[英]How to obtain navbar child component state in parent App.js?

TL;DR:我想將 Navbar 組件的點擊結果傳遞給它的父 App 組件。

我有一個在Navbar.js中呈現的App.js ,導航欄上有幾個選項卡。 App.js中,還有幾個基於導航欄上的點擊事件呈現的Card.js組件,例如,用戶點擊導航欄上的“食物”, App.js應該顯示所有“食物”卡片。 現在在App.js中,我想知道在導航欄上單擊了哪個選項卡。 下面是一些代碼:

Navbar.js(子組件)

class Navbar extends React.Component {
  constructor(props) {
    super(props);
    this.state = {currentTab: null};
    this.findTab = this.findTab.bind(this);
  }
  findTab(){
    this.setState({currentTab: 'Food'}) // here onClick the state of navbar is set to 'Food'
  }
  render(){
    return (
      <Navbar>
        <Navbar.item onClick={() => this.findTab(tab)}>
        </Navbar.item>
      </Navbar>
    )
  }
}

App.js(父組件):

class App extends React.Component {
  constructor(props){
    super(props);
    this.state = {currentCategory: null};
    this.renderCards = this.rendercards.bind(this);
  }
  renderCards(){
    const category = 'Food' // here I need to know on Navbar.item, user clicked and set the state to 'Food', so I can make category = 'Food'
    this.setState({currentCategory: category});
  }
  render(){
    return(
      <Navbar />
      <Card currentCategory={this.state.currentCategory} />
    )
  }
}

如您所見,我在點擊時將Navbar.js state 設置為“食物”,我不確定這是否是將數據傳遞給其父項的正確方法。

好吧,根據我的理解,這種情況可以通過簡單地將renderCards()作為道具傳遞到 Navbar.js 組件中來輕松處理。

有關道具及其使用方法的更多詳細信息,請通過 Reactjs 文檔 go。 組件和道具

以下是實現App.js渲染正確卡片所需的更改。

Navbar.js中,您必須使用this.props.renderCards('Food') Onclick。代替“Food”,您可以傳遞不同的類別。

class Navbar extends React.Component {
  constructor(props) {
    super(props);
    this.state = {currentTab: null};
    this.findTab = this.findTab.bind(this);
  }
//we do not need findTab method to achieve your renderCard().
  findTab(){
    this.setState({currentTab: 'Food'}) // here onClick the state of navbar is set to 'Food'
  }
  render(){
    return (
      <Navbar>
        <Navbar.item onClick={() => this.props.renderCards('Food')}>
        </Navbar.item>
      </Navbar>
    )
  }
}

App.js 中

您將this.renderCards()作為Navbar組件中的道具傳遞。

class App extends React.Component {
  constructor(props){
    super(props);
    this.state = {currentCategory: null};
    this.renderCards = this.rendercards.bind(this);
  }
  renderCards(category){
  // here we will get the actual category as a parameter of the method.
    this.setState({currentCategory: category});
  }
  render(){
    return(
      <Navbar renderCards={this.renderCards} />
      <Card currentCategory={this.state.currentCategory} />
    )
  }
}

總結:props 是將數據從子級傳遞給父級或父級傳遞給子級的最佳方式。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM