为什么我无法在进行外部点击时使用 react js 访问我的两个容器的当前目标值?

问题描述

使用这个 https://codedaily.io/tutorials/Create-a-Dropdown-in-React-that-Closes-When-the-Body-is-Clicked,我找到了我的解决方案,使我的下拉菜单在点击外部其他任何地方时关闭

但问题是,我有两个相似的下拉组件来应用这个组件,所以当我应用我的最后一个下拉列表时,我的最后一个下拉列表工作正常,但不是第一个。我不明白为什么?任何人都可以帮我解决这个问题。

    this.container = React.createRef();
    this.state = {
      open: false,};
    componentDidMount() {
      document.addEventListener("mousedown",this.handleClickOutside);
    }
    componentwillUnmount() {
      document.removeEventListener("mousedown",this.handleClickOutside);
    }
    handleClickOutside = (event) => {
     if (
       this.container.current &&
       !this.container.current.contains(event.target)
      ) {
    this.setState({
      open: false,});
   }
   };

在我的身体 div,

   <div className="container" ref={this.container}>
     {this.state.open && <div>mydropdown1</div>}
   </div>
   <div className="container" ref={this.container}>
     {this.state.open && <div>mydropdown2</div>}
   </div>

或者我可以使用 react-foco 吗?

解决方法

您需要考虑以下几点才能完成工作,

  1. 两个下拉容器的两个独立引用。

  2. 维护两个不同的状态变量

  3. 需要分别处理 refs 和按钮单击的 handleClickoutside 和 handleButtonClick 方法中的情况。参考下面的代码

    container1 = React.createRef();
    container2 = React.createRef();
    state = {
        open1: false,open2: false,};
    
    componentDidMount() {
       document.addEventListener('mousedown',this.handleClickOutside);
    }
    componentWillUnmount() {
       document.removeEventListener('mousedown',this.handleClickOutside);
    }
    
    handleClickOutside = (event) => {
           if (
              this.container1.current &&
              !this.container1.current.contains(event.target)
              ) {
                  this.setState({open1: false});
              }
          if (
             this.container2.current &&
             !this.container2.current.contains(event.target)
             ) {
                 this.setState({open2: false});
              }
           };
      }
    
    handleButtonClick = (containerNumber) => {
             this.setState({[containerNumber]: !this.state[containerNumber]});
         };
     // your code