直到最近,这在 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,现在是你可以渲染的 React 组件:
// 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 组件,您可以像任何其他 React 组件一样制作 primary:
<Button>Normal</Button>
<Button primary>Primary</Button>
现在是主题方面。我们导出一个名为 ThemeProvider 的组件,您可以将 theme 传递给它并将您的应用(或应用的一部分)包装在:
import { ThemeProvider } from 'styled-components';
const theme = {
main: 'mediumseagreen',
};
ReactDOM.render(
<ThemeProvider theme={theme}>
<MyApp />
</ThemeProvider>,
myElem
);
现在,ThemeProvider 中的任何样式组件,无论上下文有多深,都会将这个 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)