繁体   English   中英

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

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

我试图根据其状态显示/隐藏一个组件,并且我想在单击第三个组件时对其进行更改。

//导航栏

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}

//外部组件,负责检测外部是否发生了点击。

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
}

我的疑问是如何根据在Outside component内部检测到的事件来更改导航栏中的状态?

在父级中,您需要向下到事件处理程序之外:

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

在外部,只需在事件触发时调用toggleNofitication

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

暂无
暂无

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

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