使用带有 Drawer 组件的 Material-UI Box 组件

IT技术 reactjs material-ui
2022-07-31 01:20:56

Material-UI Box 组件允许我们引用其他组件,如下所示:

import Button from "@material-ui/core/Button";
import Box from "@material-ui/core/Box";

const NewButton = ({ children }) => (
  <Box compoment={Button} px={3} py={1} color="white" bgcolor="primary.dark">
    {children}
  </Box>
)

这就像我想要的那样工作。但是,现在让我尝试使用 Drawer 组件:

import Drawer from "@material-ui/core/Drawer";
import Box from "@material-ui/core/Box";

const NewDrawer = ({ children, open }) => {
  return (
    <Box component={Drawer} width="300px" bgcolor="secondary.dark">
      {children}
    </Box>
  )
}

不起作用

知道为什么不以及如何让它工作吗?

谢谢。

2个回答

根据 Material UI 文档,对于Drawer组件,我们必须将openprop 传递为true.

并且还需要像下面这样传递抽屉内容,

<Drawer open={true}>{renderContents()}</Drawer>

在 Box 组件api中,我们可以将组件数据作为“函数”传递。像下面的例子。

import Drawer from "@material-ui/core/Drawer";
import Box from "@material-ui/core/Box";

const NewDrawer = ({ children, open }) => {
  return (
    <Box component={() => {
      return <Drawer open={true}>{renderContents()}</Drawer>
    }} width="300px" bgcolor="secondary.dark">
      {children}
    </Box>
  )
}

请参阅我的代码沙箱示例。

将 aDrawertemporary变体(默认值)一起使用时,该classNameprops将应用于 Modal,它不是您尝试设置样式的元素。

相反,您希望将样式应用到DrawerBox中的Paper 元素您可以使用 Box 子项的render props 方法来完成此操作,如下面的示例所示。

import React from "react";
import Drawer from "@material-ui/core/Drawer";
import Box from "@material-ui/core/Box";
import Button from "@material-ui/core/Button";

const BoxDrawer = explicitProps => {
  return (
    <Box width="300px" bgcolor="secondary.dark">
      {({ className }) => (
        <Drawer {...explicitProps} PaperProps={{ className: className }} />
      )}
    </Box>
  );
};
export default function App() {
  const [open, setOpen] = React.useState(false);
  return (
    <div className="App">
      <Button variant="contained" onClick={() => setOpen(!open)}>
        Open Drawer
      </Button>
      <BoxDrawer open={open} onClose={() => setOpen(false)}>
        <div style={{ textAlign: "center" }}>
          <h1>Hello CodeSandbox</h1>
          <Button variant="contained" onClick={() => setOpen(!open)}>
            Close Drawer
          </Button>
        </div>
      </BoxDrawer>
    </div>
  );
}

编辑框抽屉