2017-04-06 51 views
1

我正在將styled components用於新項目,並且想要使用庫的主題化功能。我正在努力弄清楚是否有向一個對象添加多個樣式屬性的好方法或最佳實踐方法(即創建一種繼承)。現在想要的是:將多個樣式屬性添加到具有樣式組件的單個主題屬性

// in the theme, define a group of styles for a given component 
// e.g. all fonts have a font-family, weight, size, etc 
const theme = { 
    fonts: { 
    font-family: ..., 
    font-weight: ..., 
    font-size: ..., 
    } 
} 

// then in my styled component, 
// define the multi-line theme, along with component specific styles 
// or even override the theme styles 
const Header = styled.span` 
    ${props => props.theme.fonts}; 
    text-decoration: underline; 
    ... 
`; 

現在,對我來說,只有在我看來,您需要將主題屬性傳遞給組件上的每個樣式。有沒有一種模式可以幫助減少我上面例子中看到的一些重複代碼?

回答

1

我最常做的是在一個單獨的文件來定義主題風格,例如

  • MyComponent的
    • index.js
    • styles.js // < - 自定義樣式組件
  • 主題
    • spacing.js // < - 通用樣式的所有組件
    • colors.js
    • fonts.js

裏面spacing.js我想有這樣的事情:

const verticalPaddingSmall = { 
    paddingTop: 5, 
    paddingBottom: 5, 
}; 

const verticalPaddingMedium = { 
    paddingTop: 10, 
    paddingBottom: 10, 
}; 

export default function spacing(size, direction, isPadding) { 
    // some logic to return the correct object based on the params, 
    // screen size (tablets vs phones), etc... 
    return verticalPaddingSmall; 
} 

顯然,該代碼是基於我爲不同屏幕尺寸等定義的一些配置自動生成的,但最終結果是somethi ng與此類似。

然後在我的自定義組件我導入常見的樣式,並將其應用到樣式和覆蓋,如果需要它,像這樣的styles.js

import spacing from 'themes/spacing'; 
import fonts from 'themes/fonts'; 

const verticalPaddingSmall = StyleSheet.create({ 
    main: { 
    ...spacing('small', 'vertical', true), 
    }, 
    title: { 
    ...spacing('xsmall', 'horizontal', false), 
    ...fonts.title, 
    fontSize: 25, //<--- overwrite default values from title 
    }, 
}); 

我很少覆蓋上的組件的風格,因爲我常見的樣式處理表格和手機的不同風格,有點像網絡上的媒體查詢。

+0

對不起,我應該已經說得更清楚了。樣式組件是一個在React組件中使用CSS的庫。我編輯了問題以鏈接到庫源代碼。 – bgmaster