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

时间:2018-10-24 03:13:55

标签: javascript reactjs

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

// 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}

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

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内部检测到的事件来更改导航栏中的状态?

1 个答案:

答案 0 :(得分:2)

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

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

在外部,只需在事件触发时致电toggleNofitication

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