所以关于
Button
组件的文档有多个部分,还有一个链接在https://codesandbox.io/s/npie4的Codesandbox
但是,没有提到如何根据需要更改按钮的形状。
我正在使用 Google Material Sketch file,我希望按钮是圆形的
我如何使用
theme
对象来做到这一点,以便在我的整个应用程序中,Button
组件始终是圆形的?
主题中有全局边框半径形状值。你可以这样改变它:
const theme = createMuiTheme({
shape: {
borderRadius: 8,
},
})
或者,如果您只对按钮样式感兴趣:
const theme = createMuiTheme({
overrides: {
MuiButton: {
root: {
borderRadius: 8,
},
},
},
})
或者,您可以定位按钮的全局类名:
.MuiButton-root {
border-radius: 8px;
}
在 Material UI v5.0+ 中,您可以通过以下方式轻松实现:
<Button type="submit" color="primary" sx={ { borderRadius: 28 } }>Enter</Button>
如果你想重复使用相同的样式,你可以从外部文件导入它,你的代码将是这样的:
<Button type="submit" color="primary" sx={ { ...styles.button.rounded } }>Enter</Button>
或者影响所有按钮 - 通过主题全局(Material UI v5):
import { createTheme } from '@mui/material';
const theme = createTheme({
components: {
MuiButton: {
styleOverrides: {
root: {
borderRadius: 28,
},
},
},
},
});
我也通过创建一个新变体(v5.0 中的新变体)来尝试它,但我认为更复杂,因为您必须通过添加的每个道具添加许多样式:
创建主题函数
MuiButton: {
defaultProps: {
variant: 'contained',
color: 'inherit'
},
styleOverrides: {
containedInherit: {
backgroundColor: '#fff'
}
},
variants: [
{
props: { variant: 'rounded' },
style: {
borderRadius: 28
}
},
{
props: { variant: 'rounded', color: 'primary' },
style: {
color: 'white',
backgroundColor: '#01697d'
}
}
]
}
此外,使用 sx prop 解决方案,您可以将变体与圆形样式(轮廓和包含)结合起来。
如果你想要一个*咳咳*圆润的
Button
,使用Fab
:
<Fab>
<Icon />
</Fab>
<Fab variant="extended">
<Icon sx={{ mr: 1 }} />
Extended
</Fab>
如何将它用作“圆形”道具? (就像在 Vuetify 中一样)
您可以在
MUI v5中添加自定义样式道具,例如
rounded
,方法是使用styled
创建具有额外样式的原始组件的增强版本以及您想要自定义的任何道具:
import MuiButton from '@mui/material/Button';
import { styled } from '@mui/material/styles';
const options = {
shouldForwardProp: (prop) => prop !== 'rounded',
};
const Button = styled(
MuiButton,
options,
)(({ theme, rounded }) => ({
borderRadius: rounded ? '24px' : null,
}));
<Button variant="contained">Rectangle</Button>
<Button variant="contained" rounded>
Round
</Button>
要全局更改
borderRadius
,您可以使用createTheme
,请注意,此方法还会影响其他引用theme.shape.borderRadius
的组件,例如Accordion
或Skeleton
:
const theme = createTheme({
shape: {
borderRadius: 5,
},
});
为什么不在
borderRadius
中添加一个makeStyles
?
const useStyles = makeStyles(theme => ({
button: {
margin: theme.spacing(1),
borderRadius: "5em"
},
input: {
display: 'none',
},
}));
我不相信有一个 material-ui 类。你可以自己制作一个自定义类来实现它:
.rounded-corners {
border-radius: 25px;
}