我有一个在Material-UI中的Popover,我想永久地将锚点设置为一个按钮,而不仅仅是在单击时使用
不幸的是,Material-UI中当前的示例使用
event.currentTarget
。我如何在typescript中实现这一点?不幸的是,Material-UI中当前的示例使用
event.currentTarget
,并且使用引用不起作用。import React,{useRef} from 'react';
import { makeStyles, createStyles, Theme } from '@material-ui/core/styles';
import Popover from '@material-ui/core/Popover';
import Typography from '@material-ui/core/Typography';
import Button from '@material-ui/core/Button';
const useStyles = makeStyles((theme: Theme) =>
createStyles({
typography: {
padding: theme.spacing(2),
},
}),
);
export default function SimplePopover() {
const classes = useStyles();
const ref = useRef(null)
return (
<div>
<Button ref={ref} variant="contained" color="primary">
Open Popover
</Button>
<Popover
open
anchorEl={ref}
anchorOrigin={{
vertical: 'bottom',
horizontal: 'center',
}}
transformOrigin={{
vertical: 'top',
horizontal: 'center',
}}
>
<Typography className={classes.typography}>The content of the Popover.</Typography>
</Popover>
</div>
);
}
这里有一个codesandbox。
open={open}
更改为open
时,它不再引用锚点了吗?https://codesandbox.io/s/popover-anchor-5xdon?file=/demo.tsx:935-946 - JöckerbuttonRef.current
是null
,因此在buttonRef
引用到<Button>
之前,您还需要将 propanchorRef
直接设置为 null,否则会导致不必要的行为。为了避免这种情况,请使用 useEffect 监听buttonRef
的变化。这是 forked codesandbox。 - hgb123useEffect
的注释突出显示 - 这为我省去了一些麻烦,但在评论区里几乎被我错过了。 - McAden