reactjs 如何将道具传递给MUI中正在“设计样式”的组件?

yv5phkfx  于 2022-12-03  发布在  React
关注(0)|答案(1)|浏览(139)

学习MUI并很好地遵循文档。但是,我尝试按照示例中的方式设置Paper组件的样式,但我希望Paper组件具有elevation={3}
如何在下面的代码中将该道具传递给Paper?

import * as React from 'react';
import { styled } from '@mui/material/styles';
import Box from '@mui/material/Box';
import Paper from '@mui/material/Paper';
import Grid from '@mui/material/Unstable_Grid2';

const Item = styled(Paper)(({ theme }) => ({
  backgroundColor: theme.palette.mode === 'dark' ? '#1A2027' : '#fff',
  ...theme.typography.body2,
  padding: theme.spacing(1),
  textAlign: 'center',
  color: theme.palette.text.secondary,
}));

export default function BasicGrid() {
  return (
    <Box sx={{ flexGrow: 1 }}>
      <Grid container spacing={2}>
        <Grid xs={8}>
          <Item>xs=8</Item>
        </Grid>
        <Grid xs={4}>
          <Item>xs=4</Item>
        </Grid>
        <Grid xs={4}>
          <Item>xs=4</Item>
        </Grid>
        <Grid xs={8}>
          <Item>xs=8</Item>
        </Grid>
      </Grid>
    </Box>
  );
}
5rgfhyps

5rgfhyps1#

您可以在Styled组件中传递prop并访问它。记住这些属性大多数是作为HTML属性传递的,所以boolean作为字符串的工作方式稍有不同。
这里有一个Codesandbox的工作示例。您可以查看我们是如何基于prop为项目添加边框的。

import * as React from "react";
import ReactDOM from "react-dom";
import { styled } from "@mui/material/styles";
import Box from "@mui/material/Box";
import Paper from "@mui/material/Paper";
import Grid from "@mui/material/Unstable_Grid2";

function App() {
  return (
    <Box sx={{ flexGrow: 1 }}>
      <Grid container spacing={2}>
        <Grid xs={8}>
          <Item border={"true"}>xs=8</Item>
        </Grid>
        <Grid xs={4}>
          <Item>xs=4</Item>
        </Grid>
        <Grid xs={4}>
          <Item>xs=4</Item>
        </Grid>
        <Grid xs={8}>
          <Item>xs=8</Item>
        </Grid>
      </Grid>
    </Box>
  );
}

const Item = styled(Paper)(({ theme, border }) => ({
  backgroundColor: theme.palette.mode === "dark" ? "#1A2027" : "#fff",
  ...theme.typography.body2,
  padding: theme.spacing(1),
  textAlign: "center",
  border: border === "true" ? "1px solid red" : "none",
  color: theme.palette.text.secondary
}));

ReactDOM.render(<App />, document.querySelector("#app"));

相关问题