简体   繁体   English

从 DOM 中删除元素后如何清除事件侦听器

[英]How to clear events listeners in react after removing an element from the DOM

The idea was to create a dropdown that listens to mouse clicks outside its elements then is destroyed.我们的想法是创建一个下拉菜单,监听其元素外的鼠标点击,然后被销毁。 I am able to have the effect I want however I am unable to clear events each time the dropdown elements are destroyed (After a couple of opening and closing the dropdown I am registering like ten clicks even if the dropdown is closed) trying to familiarize with react so your help is appreciated我能够达到我想要的效果但是我无法在每次下拉元素被销毁时清除事件(在几次打开和关闭下拉列表之后我注册了十次点击,即使下拉列表已关闭)试图熟悉做出反应,感谢您的帮助

My try, calling the component我的尝试,调用组件

RequestDropDown.create(row.id).show({
      room_id: row.id,
      setTheState: this.setTheState
    });

creating the element on click单击创建元素

class RequestDropDown extends Component {
  static create(props = {}) {
    const containerElement = document.createElement('div');
    containerElement.classList.add('RequestDropDown_container');
    document.getElementById(`table_dots_btn_${props}`).after(containerElement);
    return render(
      <RequestDropDown createDropDownProps={props} />,
      containerElement
    );
  }

The constructor and methods构造函数和方法


  constructor() {
    super();
    this.myRef = null;

    this.setmyRefRef = (element) => {
      this.myRef = element;
    };

    this.state = {
      isOpen: false,
      showDropDownProps: {},
    };
    this.handleClick = this.handleClick.bind(this);
    this.handleClickOutside = this.handleClickOutside.bind(this);
    this.show = this.show.bind(this);
  }
  componentWillMount() {
     document.addEventListener('mousedown', this.handleClick, false);

  }

  componentWillUnMount() {
    window.removeEventListener('mousedown', this.handleClick, false);
  }

  handleClick= (e)=> {
      if(this.myRef.contains(e.target)) {
          console.log('you clicked inside')
          return;
      }
      this.handleClickOutside()
  }

  handleClickOutside= async () =>{
    console.log('the click is  outside');
    this.myRef = null;
    var element = await document.getElementsByClassName('RequestDropDown_container');
    if (element.length == 0) {
        return
    }
    await element[0].parentNode.removeChild(element[0]); // tried this too    unmountComponentAtNode(element[0]);
    this.setState({
        isOpen: false
    })
  }


  async show(props = {}) {

    await this.setState({ isOpen: true, room_id: props.room_id, setTheState: props.setTheState });

  }

the render渲染


  render() {
    const { setTheState } = this.state;
    console.log(this.myRef)

    return (this.state.isOpen === true ?
      <div id="drop_down_node" ref={this.setmyRefRef}>
        <div class="confirm_modal_content">
          <div className="dropdown-content">
            <a>Room settings</a>
            <a onClick={setTheState}>standard room</a>
            <a

            // onClick={() => handleReject(row)}
            >
              deluxe room
            </a>
          </div>
        </div>
      </div> : null
    );
  }
}

export default RequestDropDown;
componentWillMount() {
    document.addEventListener('mousedown', this.handleClick, false);

}

componentWillUnMount() {
    document.removeEventListener('mousedown', this.handleClick, false);
}

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

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