MUI5中如何使用Emotion Styled组件为Button设置margin-right
你原代码存在两个关键问题:
margin: '0, 3%, 0, auto'写法错误,CSS margin值需用空格分隔,应改为margin: '0 3% 0 auto'.button选择器无效,MUI Button组件默认不会生成该类名,需用正确的选择方式。
以下是几种可行的解决方案:
方案一:使用MUI内置Button类名选择
直接通过MUI Button的根类名MuiButton-root选中子元素:
const Wrapper = styled(Box)({ display: 'flex', margin: '0 3% 0 auto', '& .MuiButton-root': { marginRight: '40px', }, });
方案二:给Button添加自定义类名
给目标Button添加自定义类名,再在Wrapper中选中:
const Wrapper = styled(Box)({ display: 'flex', margin: '0 3% 0 auto', '& .custom-login-button': { marginRight: '40px', }, }); // 组件使用 <Wrapper> <Button variant='contained' className="custom-login-button">Login</Button> <Typography>Become a Seller</Typography> <Typography>More</Typography> </Wrapper>
方案三:直接封装Styled Button
如果仅需给该Button设置样式,可直接用styled封装Button组件:
const StyledLoginButton = styled(Button)({ marginRight: '40px', }); const Wrapper = styled(Box)({ display: 'flex', margin: '0 3% 0 auto', }); // 组件使用 <Wrapper> <StyledLoginButton variant='contained'>Login</StyledButton> <Typography>Become a Seller</Typography> <Typography>More</Typography> </Wrapper>
方案四:使用MUI sx属性(更简洁)
无需额外封装样式,直接给Button添加sx属性设置样式:
const Wrapper = styled(Box)({ display: 'flex', margin: '0 3% 0 auto', }); // 组件使用 <Wrapper> <Button variant='contained' sx={{ marginRight: '40px' }}>Login</Button> <Typography>Become a Seller</Typography> <Typography>More</Typography> </Wrapper>
内容的提问来源于stack exchange,提问作者Krishnadev. V
相关产品推荐
相关产品推荐

