检测点击外部组件反应钩

时间:2019-01-27 18:48:25

标签: javascript reactjs ecmascript-6

我正在尝试使用react挂钩来确定用户是否在元素外部单击。我正在使用useRef来获取对该元素的引用。

谁能看到解决方法。我收到以下错误并关注answers from here

  

类型“ RefObject”上不存在属性“包含”

上面的错误似乎是打字稿问题。

有一个code sandbox here,但错误有所不同。

在两种情况下都无法正常工作。

import React, { useState, useEffect, useRef } from 'react';
import ReactDOM from 'react-dom';

const Menu = () => {
    const wrapperRef = useRef<HTMLDivElement>(null);
    const [isVisible, setIsVisible] = useState(true);

    // below is the same as componentDidMount and componentDidUnmount
    useEffect(() => {
        document.addEventListener('click', handleClickOutside, true);
        return () => {
            document.removeEventListener('click', handleClickOutside, true);
        };
    }, []);


    const handleClickOutside = event => {
       const domNode = ReactDOM.findDOMNode(wrapperRef);
       // error is coming from below
       if (!domNode || !domNode.contains(event.target)) {
          setIsVisible(false);
       }
    }

    return(
       <div ref={wrapperRef}>
         <p>Menu</p>
       </div>
    )
}

3 个答案:

答案 0 :(得分:5)

useRef API应该这样使用:

import React, { useState, useRef, useEffect } from "react";
import ReactDOM from "react-dom";

function App() {
  const wrapperRef = useRef(null);
  const [isVisible, setIsVisible] = useState(true);

  // below is the same as componentDidMount and componentDidUnmount
  useEffect(() => {
    document.addEventListener("click", handleClickOutside, false);
    return () => {
      document.removeEventListener("click", handleClickOutside, false);
    };
  }, []);

  const handleClickOutside = event => {
    if (wrapperRef.current && !wrapperRef.current.contains(event.target)) {
      setIsVisible(false);
    }
  };

  return (
    isVisible && (
      <div className="menu" ref={wrapperRef}>
        <p>Menu</p>
      </div>
    )
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

答案 1 :(得分:0)

从名为Andaristuse-onclickoutside中检出该库。

import * as React from 'react'
import useOnClickOutside from 'use-onclickoutside'

export default function Modal({ close }) {
  const ref = React.useRef(null)
  useOnClickOutside(ref, close)

  return <div ref={ref}>{'Modal content'}</div>
}

答案 2 :(得分:0)

另一种解决方案是使用全屏隐形框。

import React, { useState } from 'react';

const Menu = () => {

    const [active, setActive] = useState(false);

    return(

        <div>
            {/* The menu has z-index = 1, so it's always on top */}
            <div className = 'Menu' onClick = {() => setActive(true)}
                {active
                ? <p> Menu active   </p>
                : <p> Menu inactive </p>
                }
            </div>
            {/* This is a full-screen box with z-index = 0 */}
            {active
            ? <div className = 'Invisible' onClick = {() => setActive(false)}></div>
            : null
            }
        </div>

    );

}

和CSS:

.Menu{
    z-index: 1;
}
.Invisible{
    height: 100vh;
    left: 0;
    position: fixed;
    top: 0;
    width: 100vw;
    z-index: 0;
}