简体   繁体   English

单击另一个组件即可更改反应组件的状态

[英]Change a react component's state on a click of another component

I am trying to show/hide a component based on its state and I want to change it on a click in a 3rd component. 我试图根据其状态显示/隐藏一个组件,并且我想在单击第三个组件时对其进行更改。

//navbar //导航栏

export class NavigationBar extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      showNotification: false,
    }
  }

  handleNotification = () => this.setState({
    showNotification: !this.state.showNotification,
  });

  { this.state.showNotification ? <Outside><Notifications /></Outside> : null}

//outside component, responsible for detect if a click happened outside it. //外部组件,负责检测外部是否发生了点击。

export default class Outside extends Component {
  constructor(props) {
    super(props);
    this.setWrapperRef = this.setWrapperRef.bind(this);
    this.handleClickOutside = this.handleClickOutside.bind(this);
  }
  componentDidMount() {
     document.addEventListener('mousedown', this.handleClickOutside)
  }

  setWrapperRef(node) {
    this.wrapperRef = node;
  }

  handleClickOutside(event) {
    if(this.wrapperRef && !this.wrapperRef.contains(event.target)) {
      console.log("clicked outside notifications");
      this.setState({
        showNotification: false
      })
    }
  }

  render() {
    return (
      <div ref={this.setWrapperRef}>
         {this.props.children}
      </div>
    )
  }
}

Outside.propTypes = {
  children: PropTypes.element.isRequired
}

My doubt is how can I change the state in navbar based on the event that is being detected inside Outside component ? 我的疑问是如何根据在Outside component内部检测到的事件来更改导航栏中的状态?

In parent, you need downward to Outside a event handler: 在父级中,您需要向下到事件处理程序之外:

<Outside toggleNofitication={this.handleNotification}><Notifications /></Outside>

and in Outside, just call toggleNofitication when event fired: 在外部,只需在事件触发时调用toggleNofitication

handleClickOutside = () => {
    // ...
    this.props.toggleNofitication()
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM