【问题标题】:Use media query breakpoint inside global styles with Chakra UI通过 Chakra UI 在全局样式中使用媒体查询断点
【发布时间】:2022-01-15 22:59:24
【问题描述】:

我正在尝试在 Chakra UI global styles 中使用媒体查询断点。

这是我尝试过的,但是you can't use template literals for property names

import { ChakraProvider, extendTheme } from "@chakra-ui/react";

const theme = extendTheme({
  styles: {
    global: (props) => ({
      `@media screen and (max-width: ${props.theme.breakpoints.sm})`: {
        div: {
          border: "1px solid",
        },
      },
    }),
  }
});

function App() {
  return (
    <ChakraProvider theme={theme}>
      <div>Hello world!</div>
    </ChakraProvider>
  );
}

export default App;

我也尝试连接属性名称,但它也无效:

const theme = extendTheme({
  styles: {
    global: (props) => ({
      "@media screen and (max-width: " + props.theme.breakpoints.sm + ")": {
        div: {
          border: "1px solid",
        },
      },
    }),
  }
});

我发现解决它的唯一方法是对值进行硬编码,而不是从props.theme 读取它:

const theme = extendTheme({
  styles: {
    global: {
      "@media screen and (max-width: 30em)": {
        div: {
          border: "1px solid",
        },
      },
    },
  }
});

还有其他方法可以解决这个问题吗?我在文档中找不到这种情况。

【问题讨论】:

    标签: javascript reactjs chakra-ui


    【解决方案1】:

    您可以使用bracket notation 访问动态属性名称。

    const theme = extendTheme({
      styles: {
        global: (props) => ({
           [`@media screen and (max-width: ${props.theme.breakpoints.sm})`] : {
            div: {
              border: "1px solid",
            },
          },
        }),
      }
    }); 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-04-12
      • 2013-11-24
      • 1970-01-01
      • 1970-01-01
      • 2015-06-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多