【发布时间】:2021-01-27 06:45:10
【问题描述】:
我试图了解有条件地显示工具提示的最佳方式,基于兄弟组件Popper 是否打开。我想在其子ButtonBase 悬停时默认显示它。如果Popper 打开,我希望工具提示永远打开。工具提示标题作为 Popper 关闭时选项列表中所选内容的摘要,在 Popper 打开时打开它并不理想且混乱。我是钩子的新手,所以试图了解如何结合一个钩子来根据条件需要正确设置 tooltipOpen 状态。
export default function TooltipWithPopper() {
const classes = useStyles();
const [anchorEl, setAnchorEl] = React.useState(null);
const [value, setValue] = React.useState([options[1], options[11]]);
const [pendingValue, setPendingValue] = React.useState([]);
const [tooltipOpen, setTooltipOpen] = React.useState(false);
const handleClick = (event) => {
setPendingValue(value);
setAnchorEl(event.currentTarget);
setTooltipOpen(false);
};
const handleClose = (event, reason) => {
if (reason === "toggleInput") {
return;
}
setValue(pendingValue);
if (anchorEl) {
anchorEl.focus();
}
setAnchorEl(null);
};
const open = Boolean(anchorEl);
const id = open ? "github-label" : undefined;
return (
<React.Fragment>
<div className={classes.root}>
<Tooltip title={value.map((i) => i.title).join(", ")}>
<ButtonBase
disableRipple
className={classes.button}
aria-describedby={id}
onClick={handleClick}
>
<span>Label</span>
{value.length}/{options.length}
</ButtonBase>
</Tooltip>
</div>
<Popper
id={id}
open={open}
anchorEl={anchorEl}
placement="bottom-start"
className={classes.popper}
>
<Autocomplete
open
onClose={handleClose}
multiple
classes={{
paper: classes.paper,
option: classes.option,
popperDisablePortal: classes.popperDisablePortal
}}
value={pendingValue}
onChange={(event, newValue) => {
setPendingValue(newValue);
}}
disableCloseOnSelect
disablePortal
renderTags={() => null}
noOptionsText="No labels"
.....
/>
</Popper>
</React.Fragment>
);
}
这是一个应用于触发元素的工具提示的演示。如何将其设置为仅根据其他组件的状态打开?我尝试在打开Popper 时调用handleClick 时添加setTooltipOpen(false) 调用。
演示:https://codesandbox.io/s/material-demo-forked-0wgyh?file=/demo.js:0-6181
【问题讨论】:
标签: reactjs react-hooks material-ui tooltip popper.js