【问题标题】:How to remove outline from Material UI button using by breakpoint如何使用断点从 Material UI 按钮中删除轮廓
【发布时间】:2021-10-01 20:36:40
【问题描述】:
我想删除中小断点处的outlined 变体。为此,我尝试执行以下操作:
const variantType = theme.breakpoints.down('md') ? '' : 'outlined';
<Button name="buyFood" variant={variantType} onClick={this.openFoodModal}>
Buy
</Button>;
这不起作用。我已经尝试过研究,以前似乎没有人问过这个问题。所以这是同类中的第一个。哈哈
【问题讨论】:
标签:
javascript
reactjs
bootstrap-4
material-ui
conditional-statements
【解决方案1】:
如果您有自定义主题,您可以使用 useTheme 挂钩访问您的主题设置。
之后,您只需将当前窗口width 与您的断点进行比较。
为此,您可以简单地编写一个挂钩,为您提供当前窗口width。
Here is an elegant solution from @QoP
这可能看起来像这样:
./App.js
import React from "react";
import { useTheme } from "@material-ui/core/styles";
import { Button } from "@material-ui/core";
import useWindowWidth from "./useWindowWidth";
export default function App() {
const theme = useTheme();
const width = useWindowWidth();
const variantType = width < theme.breakpoints.values.md ? "text" : "outlined";
return (
<div className="App">
<Button name="buyFood" variant={variantType} onClick={this.openFoodModal}>
Smart Suggest
</Button>
</div>
);
}
./useWindowWidth.js
import { useState, useEffect } from "react";
const getWindowWidth = () => window.innerWidth;
export default function useWindowWidth() {
const [windowWidth, setWindowWidth] = useState(getWindowWidth());
useEffect(() => {
function handleResize() {
setWindowWidth(getWindowWidth());
}
window.addEventListener("resize", handleResize);
return () => window.removeEventListener("resize", handleResize);
}, []);
return windowWidth;
}
现场演示:
【解决方案2】:
您可以使用 Material UI 中的 useTheme 和 useMediaQuery 挂钩来完成此操作。
import { Button, useTheme, useMediaQuery } from '@material-ui/core'
export default function App() {
const theme = useTheme();
const mediumDown = useMediaQuery(theme.breakpoints.down('md'));
return (
<div className="App">
<Button name="buyFood" variant={mediumDown? 'text' : 'outlined' } onClick={this.openFoodModal}>
Smart Suggest
</Button>
</div>
);
}