【问题标题】:Button click show/hide in React componentsReact 组件中的按钮单击显示/隐藏
【发布时间】:2020-05-09 12:20:57
【问题描述】:

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

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;

【问题讨论】:

标签: javascript reactjs object redux react-redux


【解决方案1】:

您的主页组件:

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.

如果你得到这个,请告诉我。

【讨论】:

    猜你喜欢
    • 2020-04-24
    • 1970-01-01
    • 2016-05-21
    • 2021-06-14
    • 2021-01-23
    • 2013-01-16
    • 1970-01-01
    • 1970-01-01
    • 2021-08-05
    相关资源
    最近更新 更多