如何在我的 Reactjs 应用程序中关闭此模式,样式为 Material UI

How can I make this modal close onMouseLeave in my Reactjs application, styled with Material UI

我有一个打开 onMouseEnter 的模式,效果很好,但是,当用户停止将鼠标悬停在按钮上时,我无法在 onMouseLeave 上关闭它。

这是我的组件:

我尝试将事件侦听器 onMouseLeave 添加到按钮标记,但它无法正常工作。有什么想法吗?

import React from 'react';
import { makeStyles } from '@material-ui/core/styles';
import Modal from '@material-ui/core/Modal';
import Backdrop from '@material-ui/core/Backdrop';
import Fade from '@material-ui/core/Fade';

const useStyles = makeStyles(theme => ({
  modal: {
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
  },
  paper: {
    backgroundColor: theme.palette.background.paper,
    border: '2px solid #000',
    boxShadow: theme.shadows[5],
    padding: theme.spacing(2, 4, 3),
  },
}));

const DistributionLineOverflow = props => {
  const classes = useStyles();
  const [open, setOpen] = React.useState(false);

  const handleOpen = () => {
    setOpen(true);
  };

  const handleClose = () => {
    setOpen(false);
  };

  return (
    <div>
      <button type="button" onMouseEnter={handleOpen}>
        i
      </button>
      <Modal
        aria-labelledby="transition-modal-title"
        aria-describedby="transition-modal-description"
        className={classes.modal}
        open={open}
        onClose={handleClose}
        closeAfterTransition
        BackdropComponent={Backdrop}
        BackdropProps={{
          timeout: 500,
        }}
      >
        <Fade in={open}>
          <div className={classes.paper}>
            <p id="transition-modal-description">
              Service Dates: {props.serviceDates}
            </p>
          </div>
        </Fade>
      </Modal>
    </div>
  );
};

export default DistributionLineOverflow;
import React, { useState, useEffect } from "react";
import ReactDOM from "react-dom";

import "./styles.css";

function App() {
  const [open, setOpen] = useState(false);

  const handleOpen = () => {
    setOpen(true);
  };

  const handleClose = () => {
    setOpen(false);
  };

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
      <button
        onMouseEnter={() => handleOpen()}
        onMouseLeave={() => handleClose()}
      >
        i
      </button>
      <div
        style={{
          width: 500,
          height: 500,
          backgroundColor: "blue",
          display: open ? "block" : "none"
        }}
      />
    </div>
  );
}

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

尝试像这样调用您的方法。

我创建了一个具有类似行为的代码沙箱:https://codesandbox.io/s/crazy-meninsky-7fl2o

我更新了 codesandbox link,但是 codesandbox 似乎有一些问题 运行 它对我来说所以我也在这里发布了整个代码。