简体   繁体   English

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

[英]Why i can't access my two container's current target value using react js on making outside click?

Using this https://codedaily.io/tutorials/Create-a-Dropdown-in-React-that-Closes-When-the-Body-is-Clicked i have found my solution to make my dropdown to get close on click of outside anywhere else.使用这个https://codedaily.io/tutorials/Create-a-Dropdown-in-React-that-Closes-When-the-Body-is-Clicked我找到了我的解决方案,让我的下拉菜单在点击时关闭外面的任何地方。

But problem is, i have two similar components of dropdown to get this apply, so when i apply my last dropdown was working properly but not the first one.I can't get this why?但问题是,我有两个相似的下拉组件来获得这个应用,所以当我应用我的最后一个下拉菜单时,我的最后一个下拉菜单工作正常但不是第一个。我不明白为什么? can anyone please help me on this.谁能帮我解决这个问题。

    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,
    });
   }
   };

and at my body div,在我的身体 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>

Or can i use react-foco?或者我可以使用 react-foco 吗?

You need to consider below points to get your work done,您需要考虑以下几点才能完成工作,

  1. Two separate refs for two dropdown containers.两个下拉容器的两个单独的参考。

  2. Maintain two different state variables维护两个不同的 state 变量

  3. Need to handle cases in both handleClickoutside and handleButtonClick methods for refs and button click respectively.需要在handleClickoutside 和handleButtonClick 方法中分别处理refs 和button click 的情况。 refer below code参考下面的代码

    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

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

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