我有一个打开onMouseEnter的模式,效果很好,但是,当用户停止将鼠标悬停在按钮上时,我无法在onMouseLeave上将其关闭。
这是我的组件:
我已经尝试将事件监听器onMouseLeave添加到button标记,但是它无法正常工作。有什么想法吗?
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链接,但似乎codesandbox为我运行它时遇到了一些问题,所以我也将整个代码都张贴在这里。