reactjs - styled-components:将 props 传递给另一个组件
问题描述
我正在尝试使用 TypeScript 和样式组件构建一个网格组件。我对Grid文件夹中的文件有以下内容:
- 索引.tsx
- 单元格.tsx
我想要达到的目标
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
,md
和lg
中的道具定义Cell.tsx
)。这就是我试图Cell.tsx
在这条线上实现的目标:
width: ${p.gutters === "margin" ? `calc(${p.sm.s && calcWidth(p.sm.s)} - 2rem)` : (p.sm.s && calcWidth(p.sm.s))};
我知道这不是它的工作原理,但我还没有找到从父母那里传递道具的方法。
我已经尝试了几个小时的谷歌搜索,但找不到任何东西,所以任何帮助我走上正轨的帮助将不胜感激。
解决方案
推荐阅读
- regex - 使用 seq 和 regex 选择新行并将其添加到 xml 文件
- python - 通过机器人框架在 Excel 表中写入数据/更改不起作用并获取 IndexError:列表索引超出范围
- python - SQLAlchemy 次要关系不使用 JOIN
- java - OCP(开放封闭原则)与 IoC(控制反转)有什么关系?
- angular - 通过 JSON 对象读取和迭代
- python - 计算groupby DataFrame中连续行之间的日期时间差
- temenos-quantum - 我们可以将 kony docker 部署到非 Azure 云中吗?据我了解,kony 仅支持 Azure 云的 docker
- java - 是直接在soap请求中传递用户名和密码还是在java中的请求头中传递用户名和密码更好
- javascript - 随机元素生成器
- hibernate - JAXB 依赖冲突?