gpt4 book ai didi

reactjs - 如何根据 Material UI 中的断点更改按钮 Prop

转载 作者:行者123 更新时间:2023-12-01 18:43:54 25 4
gpt4 key购买 nike

我正在尝试更改material-ui按钮上的变体和/或大小以适应不同的屏幕尺寸。例如,在“sm”断点下方不使用变量或 size="small",在“sm”上方使用变量="outlined"和/或 size="large"。

通常,我会使用 withStyles 并使用 theme.breakpoints 创建一个样式,通过使用 className 将样式应用到元素来影响更改,但是,variant 和 size 是属性。

阅读后the api ,搜索网络,并广泛摆弄,我似乎无法找出任何直接的方法来根据视口(viewport)宽度更改 Prop 。

我考虑过创建一个“宽度检测器”,然后使用一些 JS 逻辑来相应地更改按钮元素的 props,但这作为解决方案似乎有点遥远。

所以我在这里询问是否有更简单的解决方案。谢谢。

最佳答案

withWidth HOC 已根据 Material UI Docs 弃用。 .

这是现在有效的方法,结合了 useThemeuseMediaQuery

编辑:这里并不真正需要useTheme,因为useMediaQuery自动提供它作为参数。

// import { useTheme } from "@material-ui/core/styles";
import { useMediaQuery } from "@material-ui/core";
...

function ResponsiveButton() {
// const theme = useTheme();
// const isSmallScreen = useMediaQuery(theme.breakpoints.down("xs"));
const isSmallScreen = useMediaQuery(theme => theme.breakpoints.down("xs"));

const buttonProps = {
variant: isSmallScreen ? "text" : "outlined",
size: isSmallScreen ? "small" : "large"
};
return (
<Button {...buttonProps} color="primary">
Responsive Button
</Button>
);
}

export default ResponsiveButton;

关于reactjs - 如何根据 Material UI 中的断点更改按钮 Prop ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52472322/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com