将样式组件主题对象转换为样式

时间:2018-07-06 22:29:34

标签: styled-components

我有一个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,它似乎不是其“公共” API的一部分。这种情况将来可能会改变,因此存在风险。

我应该有更好的方法吗?

1 个答案:

答案 0 :(得分:1)

您是对的,使用未公开的API不是一个好主意。 由于您可以控制何时更新样式组件,因此您可能会冒险。

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

样式化组件已经很好地支持CSS对象,但是您需要一个返回CSS对象的函数。这里有一个问题:https://github.com/styled-components/styled-components/issues/1762

相关问题