如何向MUI中经styled封装的Paper组件传递elevation属性?
给定制后的Paper组件添加elevation={3}属性
你可以通过两种简单方式实现需求,MUI的styled工具会完整保留原组件的所有原生props:
方式一:全局统一设置(所有Item生效)
如果希望所有Item组件都应用elevation={3},给Item添加默认属性即可:
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, })); // 添加默认elevation属性 Item.defaultProps = { elevation: 3, };
这样所有用到Item的地方都会自动带上阴影层级3,无需重复传递属性。
方式二:单独给指定Item设置
如果只需要给部分Item添加阴影,直接在组件上传递elevation属性即可:
<Grid xs={8}> <Item elevation={3}>xs=8</Item> </Grid> <Grid xs={4}> <Item elevation={3}>xs=4</Item> </Grid>
完整示例代码(全局设置版本)
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, })); Item.defaultProps = { elevation: 3, }; 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> ); }
如果需要调整某个组件的阴影层级,直接给对应的Item传递不同数值即可,比如<Item elevation={5}>...</Item>,会覆盖默认值。
内容的提问来源于stack exchange,提问作者Trees4theForest
相关产品推荐
相关产品推荐

