将 styled-components 主题对象转换为样式

Convert styled-components theme object to style

我有一个 styled-components 主题,我想动态导入特定部分中的所有内容。

// example theme
const theme = {
  typography: {
    body: {
      fontSize: "0.875rem",
      fontWeight: 400,
      fontFamily: ["Roboto", "Helvetica", "Arial", "sans-serif"],
      lineHeight: "1.46429em",
      color: "rgba(0, 0, 0, 0.87)",
    }
  }
}

我想避免这种情况:

const Section = styled.div`
  font-size: ${theme => theme.typography.body.fontSize},
  font-weight: ${theme => theme.typography.body.fontWeight},
  font-family: ${theme => theme.typography.body.fontFamily},
  line-height: ${theme => theme.typography.body.lineHeight},
  color: ${theme => theme.typography.body.color},
`

这行得通。这正是我需要做的...

import { objToCss } from "styled-components/lib/utils/flatten";

export const Section = styled.div`
  ${props => objToCss(props.theme.typography.body)};
`

...但我正在导入 styled-components/lib/utils/flatten,这看起来不像是他们 "public" API 的一部分。这在未来可能会发生变化,因此存在风险。

有更好的方法吗?

你说得对,使用非暴露的 API 并不是一个好主意。 由于您可以控制何时更新样式化组件,因此您可能愿意承担风险。

否则,您可以使用执行此工作的众多库之一。例如:https://github.com/rofrischmann/css-in-js-utils#cssifyobjectobject

styled-components 已经很好地支持 CSS 对象,但是你需要一个 returns 一个 CSS 对象的函数。这里有一个问题:https://github.com/styled-components/styled-components/issues/1762