如何在 MUI 中使用带有 styled() 的 anchorEl?

How to use anchorEl with styled() in MUI?

我正在尝试锚定一个popover component to a button component. The problem is that this doesn't seem to work if the button is styled using styled()(我正在使用情感)。

此代码导致以下警告:MUI:提供给组件的 `anchorEl` 属性无效。

因为 anchorEl 无效,弹出窗口将简单地将自己定位在屏幕的左上角。

import { useState } from "react";
import { styled } from "@mui/material/styles";
import Popover from "@mui/material/Popover";
import Button from "@mui/material/Button";

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

  const handleClick = (event) => {
    setAnchorEl(event.currentTarget);
  };

  const handleClose = () => {
    setAnchorEl(null);
  };

  const open = Boolean(anchorEl);

  const StyledButton = styled((props) => <Button {...props} />)(
    ({ theme }) => ({
      //some styling
    })
  );

  return (
    <div>
      <StyledButton
        variant="contained"
        onClick={handleClick}
      >
        Open Popover
      </StyledButton>
      <Popover open={open} anchorEl={anchorEl} onClose={handleClose}>
        The content of the Popover.
      </Popover>
    </div>
  );
}

我发现使用 refs here 的方法略有不同,但我也不知道如何让它与 styled() 一起使用。

我的反应还很新,所以请温柔点。

我不知道为什么,但是如果您将 styled() 移出主要组件,它就会起作用。

const StyledButton = styled((props) => <Button {...props} />)(
    ({ theme }) => ({
      //some styling
    })
  );

export default function BasicPopover() {
  //[...]
}