gpt4 book ai didi

reactjs - Material ui popover如何锚定到另一个元素(与事件目标不同)

转载 作者:行者123 更新时间:2023-12-03 13:35:00 64 4
gpt4 key购买 nike

通常,当我们使用弹出窗口时,我们将鼠标事件期间的 anchor 设置为 event.currentTarget

然而,这在某些情况下是不可能的,而在其他情况下则是不受欢迎的。 - 如何直接设置popover anchor 元素?

import React from "react";
import Popover from "@material-ui/core/Popover";
import Typography from "@material-ui/core/Typography";
import Button from "@material-ui/core/Button";

export default function SimplePopover() {
const [anchorEl, setAnchorEl] = React.useState(null);

function handleClick(event) {
//setAnchorEl(event.currentTarget);
setAnchorEl(); //How to refer to the div?
}

function handleClose() {
setAnchorEl(null);
}

const open = Boolean(anchorEl);
const id = open ? "simple-popover" : undefined;

return (
<div>
<Typography>Anchor point of popover here</Typography>
<Button aria-describedby={id} variant="contained" onClick={handleClick}>
Open Popover
</Button>
<Popover
id={id}
open={open}
anchorEl={anchorEl}
onClose={handleClose}
anchorOrigin={{
vertical: "bottom",
horizontal: "center"
}}
transformOrigin={{
vertical: "top",
horizontal: "center"
}}
>
<Typography>The content of the Popover.</Typography>
</Popover>
</div>
);
}

demo

最佳答案

您可以使用 ref 来获取要用作 anchor 的任何元素。下面的示例使用 spanRef获取 Typography 渲染的元素元素。

Popover 的位置相对于 anchor 元素则依赖于 anchorOrigintransformOrigin特性。在下面的示例中,Popover 的左上角将与跨度的右下角对齐。我更改了 Typography 的组件从默认的 <p>元素至 <span>使定位更容易看到。由于 block 元素(例如 <p> )默认情况下具有 100% 宽度,即使内容不占用太多空间,因此 Popover如果 anchor 元素比视觉上明显的宽得多,则可能看起来离 anchor 很远。

import React from "react";
import Popover from "@material-ui/core/Popover";
import Typography from "@material-ui/core/Typography";
import Button from "@material-ui/core/Button";

export default function SimplePopover() {
const [anchorEl, setAnchorEl] = React.useState(null);
const spanRef = React.useRef();
function handleClick() {
setAnchorEl(spanRef.current);
}

function handleClose() {
setAnchorEl(null);
}

const open = Boolean(anchorEl);
const id = open ? "simple-popover" : undefined;

return (
<div>
<Typography component="span" ref={spanRef}>
Anchor point of popover here
</Typography>
<br />
<Button aria-describedby={id} variant="contained" onClick={handleClick}>
Open Popover
</Button>
<Popover
id={id}
open={open}
anchorEl={anchorEl}
onClose={handleClose}
anchorOrigin={{
vertical: "bottom",
horizontal: "right"
}}
transformOrigin={{
vertical: "top",
horizontal: "left"
}}
>
<Typography>The content of the Popover.</Typography>
</Popover>
</div>
);
}

Edit Use ref for anchorEl

关于reactjs - Material ui popover如何锚定到另一个元素(与事件目标不同),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56957863/

64 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com