单击按钮在React组件中显示/隐藏

时间:2020-01-23 09:16:49

标签: javascript reactjs object redux react-redux

我想知道如何在组件之间显示/隐藏, 单击下拉选项Show Data,应隐藏图像并显示文本。 我有一个Home组件,其中正在使用Option组件,单击Show Data, 应该显示文字Welcome!!!并隐藏图片,如何进行反应

import Option from "./Option";
class Home extends React.PureComponent {
 constructor(props) {
    super(props);
  }
  render() {
    return(
      <Option/>
      <img src="abc.jpg" width="100%"/>
      // after option `show data` selected, hide image and show below data
      <div>Welcome!!!</div>
    )
  }
}

class Option extends React.PureComponent{
  constructor(props) {
    super(props);
    this.state = {
      isOpen: false
    };
  }
  toggleOpen = () => this.setState({ isOpen: !this.state.isOpen });
  render(){
    const menuClass = `dropdown-menu${this.state.isOpen ? " show" : ""}`;
    return(
      <button className="btn btn-secondary dropdown-toggle" id="dropdownMenuButton"  aria-haspopup="true" type="button" data-toggle="dropdown"> Dropdown</button>
       <div className={menuClass} aria-labelledby="dropdownMenuButton">
          <a className="dropdown-item">
            Show Data
          </a>
       </div>
    )
  }
}
export default Option;

1 个答案:

答案 0 :(得分:0)

您的家庭组件:

class Home extends React.PureComponent {
 constructor(props) {
    super(props);
    this.state={
        showImage:false
    }
  }
  change = () =>{
      this.setState({
          showImage:!this.state.showImage
      })
  }
  render() {
    return(
      <>
      <Option change={this.change}/>
      {
          this.state.showImage?
              <img src="abc.jpg" width="100%"/>
            :
            <div>Welcome!!!</div>
      }
      </>
    )
  }
}

您的选项组件:

class Option extends React.Component{
  constructor(props) {
    super(props);
    this.state = {
      isOpen: false
    };
  }
  toggleOpen = () => this.setState({ isOpen: !this.state.isOpen });
  render(){
    const menuClass = `dropdown-menu${this.state.isOpen ? " show" : ""}`;
    return(
      <>
      <button onClick={()=>this.props.change()} className="btn btn-secondary dropdown-toggle" id="dropdownMenuButton"  aria-haspopup="true" type="button" data-toggle="dropdown"> Dropdown</button>
       <div aria-labelledby="dropdownMenuButton">
          <a className="dropdown-item">
            Show Data
          </a>
       </div>
      </>
    )
  }
}

我所做的是:

1.Created onchange function in home function and passed as prop to option
2.On click of button i called onchange function in Option component.
3.I am maintaining flag in Home component for conditional rendering.
4.For now i have onchange function on button click,you can have it anywhere and call it.

让我知道您是否明白了