当用户单击外部时,隐藏react引导程序吐司



我有一个使用react bootstrap创建的toast通知。如果用户点击吐司之外的任何位置,我需要将其忽略。有人知道我该怎么做?

这是我正在使用的吐司:

//what am I importing
import { Toast } from 'react-bootstrap';
//how am I using it
<Toast
    onClose={() => props.OnClose(false)}
    data-testid="toast"
    show={props.Show}
    delay={10000}
    autohide
>
    <Toast.Header closeButton={false}>
        <div>
            {props.Icon}
        </div>
        <div>
            Title
        </div>
        <div
            onClick={() => props.OnClose(false)}
        >
            <ToastClose />
        </div>
    </Toast.Header>
    <Toast.Body>
        Body text
    </Toast.Body>
</Toast>

您可以使用React钩子useRef。使用useRef钩子,我们可以很容易地访问DOM元素,在这种情况下,我们访问Toast组件,跟踪组件外发生的点击,并触发setShow(false)来更新状态并关闭Toast组件。如果用户点击Toast之外的任何位置,此代码将关闭Toast:

import { Toast } from "react-bootstrap";
import { useState, useRef, useEffect } from "react";
export default function App() {
  const [show, setShow] = useState(true);
  function useOutsideAlerter(ref) {
    useEffect(() => {
      /**
       * Close toast if clicked on outside of element
       */
      function handleClickOutside(event) {
        if (ref.current && !ref.current.contains(event.target)) {
          setShow(false);
        }
      }
      // Bind the event listener
      document.addEventListener("mousedown", handleClickOutside);
      return () => {
        // Unbind the event listener on clean up
        document.removeEventListener("mousedown", handleClickOutside);
      };
    }, [ref]);
  }
  const wrapperRef = useRef(null);
  useOutsideAlerter(wrapperRef);
  return (
    <div className="App">
      <Toast
        onClose={() => setShow(false)}
        data-testid="toast"
        show={show}
        delay={10000}
        autohide
        ref={wrapperRef}
      >
        <Toast.Header closeButton={false}>
          <div>Toast title</div>
          <div onClick={() => setShow(false)}>Close button</div>
        </Toast.Header>
        <Toast.Body>Body text</Toast.Body>
      </Toast>
    </div>
  );
}

原创帖子与更多信息:链接

最新更新