mui styled使用几种写法

968 阅读1分钟

第一种:第一种常规写法(主题色直接使用字符串写法'primary.main',)

const StyledDiv = styled('div')({
    marginTop:'1rem',
    width:'100%',
    bgcorlor:'primary.main',
})

第二种:使用主题样式的写法,主题直接取theme

const StyledButton = styled(Button)(({theme})=>({
    bgcorlor:theme.palette.primary.main,
    
}))

第三种:模板字符串写法

const styledBtn =styled(Buton)`
background-color:${(props)=>props.theme.palette.primary.main};
&:hover:{
background-color:${(props)=>props.theme.palette.error.main};}
`

第四种:使用shouldForwardProp,以防止样式化道具被传递并创建无效属性:

const MyComponent = styled('div', {
  shouldForwardProp: (props) => props !== 'bgColor',
})(({ bgColor }) => ({
  backgroundColor: bgColor,
}));

const MyThemeComponent = styled('div', {
  // Configure which props should be forwarded on DOM
  shouldForwardProp: (prop) =>
    prop !== 'color' && prop !== 'variant' && prop !== 'sx',
  name: 'MyThemeComponent',
  slot: 'Root',
  // We are specifying here how the styleOverrides are being applied based on props
  overridesResolver: (props, styles) => [
    styles.root,
    props.color === 'primary' && styles.primary,
    props.color === 'secondary' && styles.secondary,
  ],
})<MyThemeComponentProps>(({ theme }) => ({
  backgroundColor: 'aliceblue',
  padding: theme.spacing(1),
}));

第五种:SX 结合styled

const MyThemeComponent = styled('div')(
  sx({
    color: 'primary.contrastText',
    backgroundColor: 'primary.main',
    padding: 1,
    borderRadius: 1,
  }),
);