【发布时间】:2021-09-21 14:23:44
【问题描述】:
当我想从 Styled Components 迁移到 CSS Modules 时,出现了以下问题。
假设我有以下样式组件,它接受动态参数 offset 和动态 CSS 字符串 theme:
const Li = styled.li`
&.selected {
background-color: grey;
}
margin-left: ${({ offset }) => offset}px;
${({ theme }) => theme};
`;
在我的代码中,我会按以下方式使用它:
const Parent = () => (
<List>
{list.map((item) => (
<Item
key={item.id}
id={item.id}
selectedIds={[]}
offset={24}
theme={`
&.selected {
background-color: green;
}
`}
>
{item.name}
</Item>
))}
</List>
);
const Item = ({ id, offset = 0, theme, children }) => {
return (
<Li
theme={theme}
offset={offset}
className={selectedIds.includes(id) && 'selected'}
>
{children}
</Li>
);
};
要求:现在我真的会保留Item 的组件API:传递number 偏移量和样式字符串theme。所以基本上Parent 组件中的所有内容都应该保持这种状态。
如何在内部转换 Item 组件以使用 CSS 模块而不是样式化的 Li 组件?
【问题讨论】:
标签: css reactjs styled-components css-modules