我正在使用 Material-UI我正在尝试将一个固定组件放置在锚定菜单的顶部,也就是说我有一个按钮,我单击它然后显示一个菜单。我需要在此菜单上放置一个组件并使其始终可见,如下所示:
但是当我向下滚动时,组件也会滚动。尽管滚动的位置,我需要保持这个可见。
这些是我一直在尝试的方法:
const renderMenu = () => {
const items = [];
for (let i = 0; i < 20; i += 1) {
items.push(`Item ${i + 1}`);
}
return (
<>
{"Test one"} <-----
<Menu
id="simple-menu"
anchorEl={anchorEl}
keepMounted
PaperProps={{
style: {
maxHeight: "200px"
}
}}
open={Boolean(anchorEl)}
onClose={handleClose}
>
{"Test two"} <-----
{items.map((item) => (
<MenuItem onClick={handleClose}>{item}</MenuItem>
))}
</Menu>
</>
);
};
return (
<>
<Button
aria-controls="simple-menu"
aria-haspopup="true"
onClick={handleClick}
style={{ float: "right" }}
>
Click on me
</Button>
{anchorEl && renderMenu()}
</>
);
Test one
显示在弹出窗口和 Test two
之外滚开。 Here是一个工作的代码框。关于如何解决这个问题的任何想法?
最佳答案
您可以使用 position: fixed
修复Test 2
的位置但是有一个限制,您需要定义 menu
的宽度和 Test 2
.
这是代码框,使用内联样式进行快速演示:
https://codesandbox.io/s/material-demo-forked-6yz0l?file=/demo.js
<MenuItem // <-- use MenuItem to wrap the Test 2 to match the menu item css as much as possible
style={{
position: "fixed", // fix the position to avoid it scrolling
backgroundColor: "#ececec",
zIndex: 1,
marginTop: "-8px", // to align with original menu top margin
width: "40%" // need to have fix width. Otherwise, it will only follow content width
borderRadius: "5px 5px 0px 0px" // add the top corner border radius to match the menu style
}}
button={false} // to stop clicking effect
>
{"Test two"}
</MenuItem>
关于ReactJS Material-UI 如何将组件固定在锚定菜单之上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67705137/