【问题标题】:Using Material-UI Box Component with the Drawer Compoment将 Material-UI Box 组件与 Drawer 组件一起使用
【发布时间】:2020-01-28 10:31:09
【问题描述】:

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

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

不起作用

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

谢谢。

【问题讨论】:

    标签: reactjs material-ui


    【解决方案1】:

    根据 Material UI 文档,对于 Drawer 组件,我们必须将 open 属性作为 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>
      )
    }
    

    参考我的code sandbox 示例。

    【讨论】:

    • 然而,这个例子并没有影响抽屉的宽度或背景颜色。
    【解决方案2】:

    当使用带有temporary 变体(默认)的Drawer 时,className 属性会得到applied to the Modal,这不是您要设置样式的元素。

    相反,您希望将Box 中的样式应用到Paper element within the Drawer。您可以使用 Box 子级的 render props approach 来完成此操作,如下面的示例所示。

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

    【讨论】:

      猜你喜欢
      • 2021-05-19
      • 2019-05-24
      • 2018-09-14
      • 2020-03-31
      • 1970-01-01
      • 2017-09-23
      • 2021-11-25
      • 1970-01-01
      • 2021-10-02
      相关资源
      最近更新 更多