gpt4 book ai didi

css - 来自样式化组件时 CSS 模块中的动态 CSS

转载 作者:行者123 更新时间:2023-12-03 21:43:33 28 4
gpt4 key购买 nike

当我想从 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 变量
  • style={{ [`--offset`]: `${offset}px` }}
    .item {
    margin-left: var(--offset);
    }
  • 您可以拥有一个专用于主题的 css 模块(文件)。在您的情况下,它有 withSelected

  • .withSelected {
    &.selected {
    background-color: green;
    }
    }
    所以你可以将它作为“主题”传递
    theme={themes.withSelected}
    这是组件的外观
    import styles from "./style.module.scss";
    import themes from "./themes.module.scss";

    const Parent = () => (
    <ul>
    {list.map((item) => (
    <Item
    key={item.id}
    id={item.id}
    selectedIds={[1]}
    offset={24}
    theme={themes.withSelected}
    >
    {item.name}
    </Item>
    ))}
    </ul>
    );

    const Item = ({ id, offset = 0, theme, children, selectedIds }) => {
    return (
    <li
    className={`${styles.item} ${theme} ${
    selectedIds.includes(id) && themes.selected
    }`}
    theme={theme}
    style={{ [`--offset`]: `${offset}px` }}
    >
    {children}
    </li>
    );
    };
    演示: https://codesandbox.io/s/styledcomponent-to-css-modules-1kbqx

    关于css - 来自样式化组件时 CSS 模块中的动态 CSS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65944330/

    28 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com