gpt4 book ai didi

javascript - 将 ref 传递给 hook 问题

转载 作者:行者123 更新时间:2023-11-29 15:10:01 24 4
gpt4 key购买 nike

我写了一个简单的钩子(Hook)来在单击按钮时显示弹出菜单,我在传递 buttonRef 时遇到问题,它似乎将它传递给组件但是元素没有正确定位,就像它一样根本没有通过。

我在 codeSanbox 上包含了一个示例:https://codesandbox.io/s/9o03qx3n3o

我已经确认这在不在钩子(Hook)内时有效,React 开发工具显示它在两个实例中传递相同的元素。我试过使用 forwardRef,同样的问题,我试过使用标准状态来存储 ref 无济于事;

--- Hook ---

const usePopperMenu = btnRef => {
const [open, setOpen] = useState(false);

const handleClose = event => {
if (btnRef.current.contains(event.target)) {
return;
}
setOpen(false);
};
const elems = ({ children }) => (
<Popper
open={open}
anchorEl={btnRef.current}
placement="bottom"
transition
disablePortal
>
{({ TransitionProps, placement }) => (
<Grow
{...TransitionProps}
id="menu-list-grow"
style={{
transformOrigin:
placement === "bottom" ? "center top" : "center bottom"
}}
>
<Paper>
<ClickAwayListener onClickAway={e => handleClose(e)}>
<MenuList>{children}</MenuList>
</ClickAwayListener>
</Paper>
</Grow>
)}
</Popper>
);
return [elems, setOpen, open];
};

--- App/Component ---

function App() {
const btnRef = useRef(null);
const [Menu, setOpen, open] = usePopperMenu(btnRef);
return (
<div className="App">
<div>
<Button
buttonRef={btnRef}
onClick={() => setOpen(!open)}
variant="outlined"
color="secondary"
>
Click Me!
</Button>
<Menu>
<MenuItem>
<Typography color="textPrimary">Menu Item 1</Typography>
</MenuItem>
<MenuItem>
<Typography color="textPrimary">Menu Item 2</Typography>
</MenuItem>
</Menu>
</div>
</div>
);
}

最佳答案

它对我很有用 - 问题出在你的 css 样式上。按钮容器是全尺寸的,display:grid 这就是下拉菜单放错位置的原因

尝试:

.App {
display: flex;
justify-content: center;
}

https://codesandbox.io/s/oprzyv665?fontsize=14

关于javascript - 将 ref 传递给 hook 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55688733/

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