Using Material-UI Box Component with the Drawer Compoment

帅比萌擦擦* 提交于 2021-02-10 12:14:07

问题


The Material-UI Box component allows us to reference other components as follows:

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>
)

This works just as I want it to. However, let me now try it with the Drawer component:

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>
  )
}

This does not work.

Any idea why not and how I can get it to work?

Thanks.


回答1:


As per Material UI doc, For the Drawer component, we have to pass the open prop as true.

And also need to pass the drawer content like below,

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

In Box component api, we can pass the component data as a 'function'. like the below example.

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>
  )
}

Refer to my code sandbox example.




回答2:


When using a Drawer with the temporary variant (the default), the className prop gets applied to the Modal which is not the element that you are trying to style.

Instead, you want to apply the styles from the Box to the Paper element within the Drawer. You can accomplish this using the render props approach for the Box children as shown in my example below.

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>
  );
}



来源:https://stackoverflow.com/questions/59946751/using-material-ui-box-component-with-the-drawer-compoment

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!