如何使用条件渲染在子组件上设置ref?

时间:2019-01-26 07:33:15

标签: reactjs refs

我希望有一个弹出式组件,当我单击日历上的事件时会显示该组件,但是当我在日历上单击该事件时会消失。

我有一个CalendarPopup组件,该组件有条件地根据道具进行渲染。当我使弹出窗口在第一个可见时有效,但以后没有出现。

在检查DOM时,我看到<div class="NaN hideClass" id="popupDIV">

export class CalendarPopup extends Component {
    render() {
        if (!!!this.props.isPopoverVisible) {
            return null;
        }
        return (
            <div className='popup_container' id="popupDIV" ref={this.props.setPopupRef}>
            </div>
export default CalendarPopup;

class CalendarContainer extends Component {
  state = {
    isPopoverVisible: false,
    isEventSelected: false,
  };

  onEventSelected = (id) => {
    this.setStateProperty('isEventSelected', true);
    this.setStateProperty('isPopoverVisible', true);
    // logic
    this.setStateProperty('isEventSelected', false);
  }

  setPopupRef = (node) => {
    this.popupRef = node
  }

  handleClick = () => {
    if (!this.props.isPopoverVisible) {
      document.addEventListener('click', this.handleOutsideClick, false);
    } else {
      document.removeEventListener('click', this.handleOutsideClick, false);
    }

    this.setStateProperty('isPopupVisible', false);
  }

  handleOutsideClick = (e) => {
    console.log(this.popupRef);
    if (this.state.isEventSelected || !!!this.state.isPopoverVisible || this.popupRef.contains(e.target)) {
      return;
    }

    this.handleClick();
  }

  setStateProperty = (property, value) => {
    this.setState({
      [property]: value,
    });
  }

  render() {
    return (
      <div onClick={this.handleOutsideClick}>
        <CalendarComponent onEventSelected={(id) => this.onEventSelected(id)}/>
        <CalendarPopup setPopupRef = { this.setPopupRef } isPopoverVisible={this.state.isPopoverVisible}/>
      </div>
    );
  }
}

我希望当我在日历上选择另一个事件时,弹出窗口再次可见

0 个答案:

没有答案