直到最近,這還不是React世界中解決的問題。
我是ElementalUI(一個React組件庫)的維護者之一,我們在過去的6-12個月裏一直在嘗試所有不同的樣式化方法。 (!)你的名字,我們已經嘗試過了。 (我在我的ReactNL keynote和他們分解的地方談到了我對一些最流行的庫的使用經驗)
問題是,目前的樣式庫都沒有內置的主題支持。你可以用一種非常好用的,非用戶友好的方式來做到這一點,但是當你發佈一個組件時,這不是你想要的,對嗎?
這就是爲什麼我們建造了styled-components
。 styled-components
有一些有趣的屬性,其中一個是將主題直接內置到庫中,使其成爲構建可分發組件的完美選擇!
下面是簡短的解釋,但我鼓勵你通過我們的documentation解釋一切!
這是什麼styled-components
的基本用法是這樣的:
import React from 'react';
import styled from 'styled-components';
// Create a <Wrapper> react component that renders a <section> with
// some padding and a papayawhip background
const Wrapper = styled.section`
padding: 4em;
background: papayawhip;
`;
這個變量,Wrapper
,現在反應的組分可以渲染:
// Use them like any other React component – except they're styled!
<Wrapper>
<Title>Hello World, this is my first styled component!</Title>
</Wrapper>
(如果你點擊圖像,你會得到一個現場操場)
當您將插值函數傳遞給帶標籤的模板文字時,我們將傳遞給該組件的屬性傳遞給您。這意味着你可以適應道具:
import styled from 'styled-components';
const Button = styled.button`
/* Adapt the colors based on primary prop */
background: ${props => props.primary ? 'palevioletred' : 'white'};
color: ${props => props.primary ? 'white' : 'palevioletred'};
font-size: 1em;
margin: 1em;
padding: 0.25em 1em;
border: 2px solid palevioletred;
border-radius: 3px;
`;
在這裏,我們創建了一個Button
組件,你可以做primary
像任何其他陣營組成:
<Button>Normal</Button>
<Button primary>Primary</Button>
現在來主題方面。我們出口一個名爲ThemeProvider
組件,您可以通過一個theme
幷包裝您的應用程序(或應用程序的部分):該ThemeProvider
內
import { ThemeProvider } from 'styled-components';
const theme = {
main: 'mediumseagreen',
};
ReactDOM.render(
<ThemeProvider theme={theme}>
<MyApp />
</ThemeProvider>,
myElem
);
現在,任何風格的組成部分,無論多麼深刻的感謝背景下,將把這個theme
注入道具。
這是一個主題化Button
會是什麼樣子:
import styled from 'styled-components';
const Button = styled.button`
/* Color the background and border with theme.main */
background: ${props => props.theme.main};
border: 2px solid ${props => props.theme.main};
/* …more styles here… */
`;
現在你Button
會把它被傳遞的theme
並改變它基於這樣的造型! (您也可以通過defaultProps
提供默認設置)
這就是styled-components
的要點,以及它如何幫助構建可分發的組件!
我們目前有WIP doc about writing third-party component libraries,我鼓勵您查看,當然,正常的文檔也是一個很好的閱讀。我們試圖涵蓋所有的基礎,所以如果你看到任何你不喜歡的或者你認爲失蹤的東西,請馬上告訴我們,我們將討論!
如果您有任何其他關於styled-components
的問題,請隨時在此回覆或在Twitter上與我們聯繫。 (@mxstbr)
你如何定製你自己的自定義組件? 只需使用div包裝? – MoeSattler
是的,我使用每個較大組件的大量樣式化組件。類似這樣的: const Btn =風格。按鈕' 風格:這裏; ' const的按鈕=(道具)=> { 回報( {props.text} ); } –
mxstbr
如何解決組件中樣式的實際耦合問題。例如,讓我們說我的所有按鈕現在都需要5px的半徑,我必須進入所有按鈕並手動更改它們。或者我讀你的帖子是錯的?或媒體查詢,你如何使用它們? –