sách gpt4 ai đã đi

CSS động trong CSS Modules khi đến từ styled-components

In lại 作者:行者123 更新时间:2023-12-03 21:43:33 35 4
mua khóa gpt4 Nike

当我想从 Styled Components 迁移到 CSS Modules 时,出现了以下问题。
假设我有以下样式组件,它接受动态参数 bù lại和一个动态 CSS 字符串 theme :

const Li = styled.li`
&.selected {
background-color: grey;
}

margin-left: ${({ offset }) => offset}px;

${({ theme }) => theme};
`;
在我的代码中,我将按以下方式使用它:
const Parent = () => (

{list.map((item) => (
<>
key={item.id}
id={item.id}
selectedIds={[]}
offset={24}
theme={`
&.selected {
màu nền: xanh lá cây;
}
`}
>
{item.name}

))}

);

const Item = ({ id, offset = 0, theme, children }) => {
trở lại (
<>
theme={theme}
offset={offset}
className={selectedIds.includes(id) && 'selected'}
>
{children}

);
};
nhu cầu:现在我真的会保留 Item的组件 API:传递 con số偏移量和样式字符串 theme .所以基本上 Parent 中的所有内容组件应该保持这种方式。
Cách chuyển đổi Item组件内部使用 CSS 模块而不是样式 Li零件?

1 Câu trả lời

这可能是一种不同于你以前的思维方式,但它可以工作

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

  • .withSelected {
    &.selected {
    màu nền: xanh lá cây;
    }
    }
    所以你可以将它作为“主题”传递
    theme={themes.withSelected}
    这是组件的外观
    import styles from "./style.module.scss";
    import themes from "./themes.module.scss";

    const Parent = () => (

      {list.map((item) => (
      <>
      key={item.id}
      id={item.id}
      selectedIds={[1]}
      offset={24}
      theme={themes.withSelected}
      >
      {item.name}

      ))}

    );

    const Item = ({ id, offset = 0, theme, children, selectedIds }) => {
    trở lại (
    <>
    className={`${styles.item} ${theme} ${
    selectedIds.includes(id) && themes.selected
    }`}
    theme={theme}
    style={{ [`--offset`]: `${offset}px` }}
    >
    {children}

    );
    };
    Thử nghiệm: https://codesandbox.io/s/styledcomponent-to-css-modules-1kbqx

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

    35 4 0
    Bài viết được đề xuất: asp.net-core - View 和静态文件的 Asp.Net Core 问题 (F#)
    Bài viết được đề xuất: javascript - 在 jQuery 中使用 $() 快捷方式是不好的做法吗?
    Bài viết được đề xuất: javascript - 获取该月的第几周
    Bài viết được đề xuất: string - 拆分文件名 - 奇怪的行为
    行者123
    Hồ sơ cá nhân

    Tôi là một lập trình viên xuất sắc, rất giỏi!

    Nhận phiếu giảm giá Didi Taxi miễn phí
    Mã giảm giá Didi Taxi
    Giấy chứng nhận ICP Bắc Kinh số 000000
    Hợp tác quảng cáo: 1813099741@qq.com 6ren.com