0

我试图弄清楚如何在默认情况下解析组件中的样式系统函数。这个想法是有一个容器元素,它使用开箱即用的主题来提供主要的响应中断。

现在我在下面做的是为 styled-systemwidth函数提供一个像这样的对象:

//theme.js
const CONTAINERS = {
  xs: "100%",
  sm: "55rem",
  md: "74rem",
  lg: "100rem",
  xl: "131rem",
};
export default {
 containers: CONTAINERS,
//other items
}
//Container.js
export default (props) => {
  const { containers, grid } = useContext(ThemeContext);
  return (
    <Container px={grid.margin} width={containers} {...props}>
      {props.children}
    </Container>
  );
};

const Container = styled("div")(
  css`
    margin-right: auto;
    margin-left: auto;
    padding-right: 1rem;
    padding-left: 1rem;
  `,
  compose
);

这确实有效,但是,它不像我想要的那样干净。我希望能够简单地拥有

const Container = styled("div")(
  css`
    margin-right: auto;
    margin-left: auto;
    padding-right: 1rem;
    padding-left: 1rem;
    ${//maybe resolve the responsive widths here}
  `,
  compose //<- a group of styled-system functions supplied in one object
  //or resolve responsive widths here
);

export default Container

这会更干净,因为我可以将布局组件合并并导出到一个文件中,而无需执行const Container...+const StyledContainer...手续。

我正在考虑编写一个循环containers对象并返回包含在媒体查询中的宽度的函数的想法,但我想知道 styled-system 是否开箱即用?

4

1 回答 1

0

我在文档中找不到任何东西可以开箱即用,所以我手动实现了它。

//theme.js
const BREAKPOINTS = {
  xs: "0em",
  sm: "37em",
  md: "48em",
  lg: "64.625em",
  xl: "84em",
};

const CONTAINERS = {
  xs: "100%",
  sm: "55rem",
  md: "74rem",
  lg: "100rem",
  xl: "131rem",
};

下面的脚本采用上面的对象并将断点值放入包装@media中,然后将容器的值插入width:其中。然后将整个批次返回为 css。

const Container = styled("div")(
  css`
    margin-right: auto;
    margin-left: auto;
    padding-right: 1rem;
    padding-left: 1rem;

    &::after,
    &::before {
      content: "";
      display: block;
      min-height: 2rem;
      height: 4vw;
      max-height: 6rem;
    }
  `,
  compose,
  (props) => {
    const breakpoints = props.theme.breakpoints;
    const containers = props.theme.containers;

    const makeMedia = (media) => {
      return (...args) => css`
        @media ${media} {
          ${css(...args)}
        }
      `;
    };

    const getMedia = Object.keys(breakpoints).reduce((media, breakpoint) => {
      const breakpointWidth = breakpoints[breakpoint];
      media[breakpoint] = makeMedia(
        [breakpoint !== 0 && `(min-width: ${breakpointWidth})`]
          .filter(Boolean)
          .join(" and ")
      );
      return media;
    }, {});

    return css`
      ${Object.keys(breakpoints).map(
        (key) => containers[key] && getMedia[key]`width: ${containers[key]}`
      )};
    `;
  }
);
于 2020-09-22T16:00:10.223 回答