我在文本字段中有一个工具提示。 它只显示在第一行,并且每次用户将鼠标悬停在该行上时。向下滚动页面时必须隐藏它。 通过执行此代码,我看不到“测试”一词。
这是我到目前为止尝试过的。
open={isHovering && index === 0}
title={(
<Typography variant="headings.h4" color='text.secondary'>Testing</Typography>
)}
placement="top"
componentsProps={{
tooltip: {
sx: {
backgroundColor: 'transparent',
},
},
}}
PopperProps={{
sx: {
'& .MuiTooltip-tooltip': {
padding: '0 5px',
},
},
modifiers: [
{
name: 'offset',
options: {
offset: [0, 10],
},
},
],
}}
>
<TextField
id="outlined-basic"
variant="standard"
placeholder="Enter amount"
type="text"
value={amount}
InputProps={{
disableUnderline: true,
value: value,
sx: {
mt: '0 !important',
px: 6,
height: 1,
},
}}
sx={{ minWidth: 160 }}
onChange={handleChange}
onBlur={handleBlur}
/>
</Tooltip>`
```
您可以添加一个事件侦听器以在窗口对象上滚动,并在用户滚动时将 isHovering 状态设置为 false。
可以像这样完成:
import { useState, useEffect, useRef } from "react";
import { TextField, Tooltip, Typography } from "@mui/material";
const MyTextField = ({ amount, handleChange, handleBlur }) => {
const [isHovering, setIsHovering] = useState(false);
const ref = useRef(null);
//useEffect hook adds an event listener for the scroll event on the window object.
When the event is fired, it sets the isHovering state to false.
useEffect(() => {
const handleScroll = () => {
setIsHovering(false);
};
window.addEventListener("scroll", handleScroll);
return () => {
window.removeEventListener("scroll", handleScroll);
};
}, []);
return (
<Tooltip
open={isHovering}
title={<Typography variant="headings.h4">Testing</Typography>}
placement="top"
PopperProps={{
modifiers: [
{
name: "offset",
options: {
offset: [0, 10],
},
},
],
}}
//enterDelay and leaveDelay props are used to add a delay before the tooltip is shown or hidden, respectively
//This can help prevent the tooltip from flickering when the user scrolls quickly.
enterDelay={500}
leaveDelay={200}
componentsProps={{
tooltip: {
sx: {
backgroundColor: "transparent",
},
},
}}
//the ref prop is addefd to the Tooltip component so that you can set the isHovering state accordingly.
//you can also use it to detect wheter the tooltip is opened or closed. and even to set isHovering state accordingly.
ref={ref}
onOpen={() => {
setIsHovering(true);
}}
onClose={() => {
setIsHovering(false);
}}
>
<TextField
id="outlined-basic"
variant="standard"
placeholder="Enter amount"
type="text"
value={amount}
InputProps={{
disableUnderline: true,
sx: {
mt: "0 !important",
px: 6,
height: 1,
},
}}
sx={{ minWidth: 160 }}
onChange={handleChange}
onBlur={handleBlur}
/>
</Tooltip>
);
};
export default MyTextField;
解释: