使用一个组件中的按钮来渲染主(App)组件中的另一个组件

时间:2019-11-03 20:29:29

标签: javascript reactjs react-component

我试图显示/隐藏一个组件ItemMain,并使用另一个组件NavLogoNew中的按钮将其导入到主App组件中。我尝试以许多不同的方式执行此操作,但是似乎按钮不知道是否单击了按钮,当我手动更改true / false时它可以工作。在Web中,我发现了很多只涉及两个组件但没有类似情况的情况。我的代码:

应用

import React from 'react';
import './App.css';
import { tsPropertySignature } from '@babel/types';
import { statement } from '@babel/template';

import NavBar from './../Components/Navigation/NavBar/NavBar.js';
import ItemMain from './../Components/Item/ItemMain/ItemMain.js';
import ItemList from './../Components/Item/ItemList/ItemList.js';
import NavButtonTop from './../Components/Navigation/NavButton/NavButtonTop/NavButtonTop.js';
import NavLogoNew from './../Components/Navigation/NavButton/NavButtonNew/NavLogoNew.js';

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      visible: false
    };
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick() {
    this.setState({
      visible: !this.visible
    })
  }     

  render() {
    return (
      <div className="App">
        <NavBar />
        {this.state.visible ? <ItemMain /> : null}
        <ItemList />
        <NavButtonTop name='UP'/>
      </div>
    );
  }
}


export default App;

NavLogoNew:

import React from 'react';
import './NavLogoNew.css';
import ItemMain from './../../../Item/ItemMain/ItemMain.js'


class NavLogoNew extends React.Component {
    render() {
        return (    
            <button 
                className='NavLogoNew'
                onClick={this.props.click}  
            >
                {this.props.name}  
            </button>
        );
    }
}

export default NavLogoNew;

1 个答案:

答案 0 :(得分:0)

您的handleClick函数缺少某些内容
使用!this.state.visible,因此请从下面进行更改

handleClick(){
    this.setState({
      visible: !this.visible
    })
  }


 handleClick = () => {
    this.setState({
      visible: !this.state.visible
    })
  }

按如下所示将handleClick函数传递给NavLogoNew

<NavLogoNew onClick = {this.handleClick} />

在NavLogoNew组件内部,您应该按以下方式调用它

class NavLogoNew extends React.Component {
    render() {
        return (    
            <button 
                className='NavLogoNew'
                onClick={() => this.props.onClick()}  
            >
                {this.props.name}  
            </button>
        );
    }
}