首页 > 解决方案 > styled-components:将 props 传递给另一个组件

问题描述

我正在尝试使用 TypeScript 和样式组件构建一个网格组件。我对Grid文件夹中的文件有以下内容:

我想要达到的目标

Grid( index.tsx) 有一个 prop( gutters),可以设置为margin. 如果是这种情况,我希望能够将此道具传递给Cell.tsx并输出不同的 CSS。

索引.tsx

import * as React from "react";
import styled, { css } from "styled-components";

import { Cell } from "./Cell";

export { default as Cell, ICellProps } from "./Cell";

export interface IGridProps {
  className?: string;
  /** Grid items */
  children: any;
  /** Grid gutters */
  gutters?: "padding" | "margin" | "none";
}

export const Grid = styled.div<IGridProps>`
  ${p => p.gutters !== "none" && css`
    margin-right: -1rem;
    margin-left: -1rem;
  `}

  ${p => p.gutters === "padding" && css`
    & > ${Cell} {
      padding-right: 1rem;
      padding-left: 1rem;      
    }
  `}

  ${p => p.gutters === "margin" && css`
    & > ${Cell} {
      margin-right: 1rem;
      margin-left: 1rem;
    }
  `}
`;

export default ({
  className,
  children,
  gutters = "none",
}: IGridProps) => (
  <Grid
    className={className}
    gutters={gutters}
  >
    {children}
  </Grid>
);

单元格.tsx

import * as React from "react";
import styled, { css } from "styled-components";

import { IGridProps } from "./";

interface ICell {
  s: number;
  offset?: number;
}

export interface ICellProps extends IGridProps {
  className?: string;
  children: any;
  sm?: ICell;
  md?: ICell;
  lg?: ICell;
}

const calcWidth = (size: number) => `${(size / 12) * 100}%`;

export const Cell = styled.div<ICellProps>`
  flex: 0 0 auto;

  min-width: 0;
  width: 100%;
  min-height: 0;

  ${p => p.sm && css`
    @media screen and (min-width: 0) {
      margin-left: ${p.sm.offset && calcWidth(p.sm.offset)};
      width: ${p.gutters === "margin" ? `calc(${p.sm.s && calcWidth(p.sm.s)} - 2rem)` : (p.sm.s && calcWidth(p.sm.s))};
    }
  `}
`;

export default ({
  className,
  children,
  sm,
  md,
  lg,
}: ICellProps) => (
  <Cell
    className={className}
    sm={sm}
    md={md}
    lg={lg}
  >
    {children}
  </Cell>
);

我想计算 [断点宽度] - 2rem(断点用sm,mdlg中的道具定义Cell.tsx)。这就是我试图Cell.tsx在这条线上实现的目标:

width: ${p.gutters === "margin" ? `calc(${p.sm.s && calcWidth(p.sm.s)} - 2rem)` : (p.sm.s && calcWidth(p.sm.s))};

我知道这不是它的工作原理,但我还没有找到从父母那里传递道具的方法。

我已经尝试了几个小时的谷歌搜索,但找不到任何东西,所以任何帮助我走上正轨的帮助将不胜感激。

标签: reactjstypescriptstyled-components

解决方案


推荐阅读