我正在尝试自定义我的按钮,所以当我的网站在移动视图上时,我想要一个小尺寸的按钮......&当我的屏幕点击 MD 断点时,我希望按钮尺寸为“大”
我当前的按钮样式 : 当前按钮样式
我试过,size={{ xs: "small", md: "large" }}
但没有用
请帮忙。
我正在尝试自定义我的按钮,所以当我的网站在移动视图上时,我想要一个小尺寸的按钮......&当我的屏幕点击 MD 断点时,我希望按钮尺寸为“大”
我当前的按钮样式 : 当前按钮样式
我试过,size={{ xs: "small", md: "large" }}
但没有用
请帮忙。
根据MUI 文档,它说按钮组件中的 size 属性将字符串作为值(“小”或“中”或“大”),因此提供具有不同断点的对象不应该起作用。
在这种情况下,我建议根据窗口断点来调节大小
const [width, setWidth] = useState(window.innerWidth)
<Button size={width < 600 ? 'small' : 'large'}>
More Details
</Button>
size
不是sx
prop 中的有效属性。只有里面的属性sx
支持响应值。如果你想根据当前宽度分配一个 prop,你需要编写一个自定义钩子:
import { Breakpoint, useTheme } from '@mui/material';
type ResponsiveValue<T> = {
[P in Breakpoint]?: T;
};
function useResponsiveProp<PropValue>(
responsiveValue: ResponsiveValue<PropValue>,
) {
// you can copy the useWidth hook definition in the official docs:
// https://mui.com/components/use-media-query/#migrating-from-withwidth
const width = useWidth();
const theme = useTheme();
const keys: readonly Breakpoint[] = [...theme.breakpoints.keys];
keys.reduce((lastNonNullValue, key) => {
if (!responsiveValue[key]) {
responsiveValue[key] = lastNonNullValue;
return lastNonNullValue;
}
return responsiveValue[key];
}, responsiveValue[keys[0]]);
return responsiveValue[width];
}
import Button, { ButtonTypeMap } from '@mui/material/Button';
type ButtonSize = ButtonTypeMap['props']['size'];
const size = useResponsiveProp<ButtonSize>({
xs: 'small',
sm: 'medium',
lg: 'large',
});