如何在父App.js中获取导航栏子组件状态?

问题描述 投票:0回答:1

TL; DR:我想将点击结果从Navbar组件传递到其父级App组件。

我有一个在Navbar.js中呈现的App.js,并且导航栏上有几个选项卡。在App.js中,还有一些基于导航栏上的click事件呈现的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状态设为“食物”,我不确定这是否是将数据传递给其父项的正确方法。

javascript reactjs
1个回答
0
投票

嗯,据我所知,通过将renderCards()作为Navbar.js组件中的道具,可以轻松解决这种情况。

有关道具及其使用方法的更多详细信息,请阅读Reactjs文档。Components and props

以下是实现App.js渲染右卡所需的更改。

Navbar.js中您必须使用this.props.renderCards('Food') Onclick。您可以通过不同的类别来代替“食品”。

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} />
    )
  }
}

摘要:道具是将数据从孩子传递给父母或从父母传递给孩子的最佳方法。

© www.soinside.com 2019 - 2024. All rights reserved.