具有样式组件的React的MaterialUI

时间:2020-02-04 18:34:55

标签: reactjs material-ui styled-components

我想为MaterialUI的Paper的{​​{1}}设置样式

Dialog

但是,这意味着嵌套在Dialog中且具有const StyledDialog = styled(Dialog)` & .MuiPaper-root { width: 600px; } `; 类的所有元素(例如,其他Papers)都将继承它。

有没有办法仅将样式限制在第一个对话框使用的Paper上?

2 个答案:

答案 0 :(得分:2)

有几种方法可以解决此问题。一种方法是使用子选择器(如Kaca992的答案所述),但是Paper不是Dialog的直接子代,因此使用此方法需要& > .MuiDialog-container > .MuiPaper-root。另一个选择是使用Dialog的PaperComponent prop并为其提供样式化的Paper组件。第三种选择是利用MuiDialog-paper CSS class

这三种方法都显示在下面的示例中。

import React from "react";
import Button from "@material-ui/core/Button";
import DialogTitle from "@material-ui/core/DialogTitle";
import Dialog from "@material-ui/core/Dialog";
import Paper from "@material-ui/core/Paper";
import styled from "styled-components";

const StyledDialog = styled(Dialog)`
  & > .MuiDialog-container > .MuiPaper-root {
    background-color: purple;
  }
`;
const StyledDialog2 = styled(Dialog)`
  & .MuiDialog-paper {
    background-color: blue;
  }
`;
const StyledPaper = styled(Paper)`
  background-color: green;
`;

export default function SimpleDialogDemo() {
  const [open1, setOpen1] = React.useState(false);
  const [open2, setOpen2] = React.useState(false);
  const [open3, setOpen3] = React.useState(false);

  return (
    <div>
      <Button variant="outlined" color="primary" onClick={() => setOpen1(true)}>
        Open dialog using child selectors
      </Button>
      <Button variant="outlined" color="primary" onClick={() => setOpen3(true)}>
        Open dialog using MuiDialog-paper
      </Button>
      <Button variant="outlined" color="primary" onClick={() => setOpen2(true)}>
        Open dialog using custom Paper
      </Button>
      <StyledDialog
        onClose={() => setOpen1(false)}
        aria-labelledby="simple-dialog-title"
        open={open1}
      >
        <DialogTitle id="simple-dialog-title">
          Paper styled via child selectors
        </DialogTitle>
      </StyledDialog>
      <StyledDialog2
        onClose={() => setOpen3(false)}
        aria-labelledby="simple-dialog-title"
        open={open3}
      >
        <DialogTitle id="simple-dialog-title">
          Paper styled via MuiDialog-paper
        </DialogTitle>
      </StyledDialog2>
      <Dialog
        onClose={() => setOpen2(false)}
        aria-labelledby="simple-dialog-title"
        open={open2}
        PaperComponent={StyledPaper}
      >
        <DialogTitle id="simple-dialog-title">
          Paper styled via custom Paper component
        </DialogTitle>
      </Dialog>
    </div>
  );
}

Edit Dialog Paper

答案 1 :(得分:1)

尝试一下:

const StyledDialog = styled(Dialog)`
  & > .MuiPaper-root {
    width: 600px;
  }
`;

css>运算符将仅接受作为对话框组件的直接子级的子级。如果这样不行,请查看其他CSS操作符:https://www.w3schools.com/cssref/css_selectors.asp

相关问题