pau*_*l23 12 reference reactjs material-ui
通常,当我们使用 popover 时,我们将鼠标事件期间的锚点设置为event.currentTarget。
然而,这在某些情况下是不可能的,而在其他情况下是不受欢迎的。- 如何直接设置弹出框锚元素?
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>
);
}
Run Code Online (Sandbox Code Playgroud)
Rya*_*ell 18
您可以使用 ref 来获取要用作锚点的任何元素:
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 divRef = React.useRef();
function handleClick() {
setAnchorEl(divRef.current);
}
function handleClose() {
setAnchorEl(null);
}
const open = Boolean(anchorEl);
const id = open ? "simple-popover" : undefined;
return (
<div ref={divRef}>
<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>
);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11707 次 |
| 最近记录: |