脚本宝典收集整理的这篇文章主要介绍了

Styled-Components

脚本宝典小编觉得挺不错的,现在分享给大家,也给大家做个参考,希望能帮助你少写一行代码,多一份安全和惬意。
<p><code></p> <h1 id="articleHeader0">Styled-Components</h1> <blockquote><p>它是通过JavaScript改变<a href="http://www.js-code.com/tag/css" title="CSS" target="_blank">CSS</a>编写方式的解决方案之一,从根本上解决常规<a href="http://www.js-code.com/tag/css" title="CSS" target="_blank">CSS</a>编写的一些弊端。<br />通过JavaScript来为<a href="http://www.js-code.com/tag/css" title="浏览关于“CSS”的文章" target="_blank" class="tag_link">CSS</a>赋能,我们能达到常规CSS所不好处理的逻辑复杂、函数方法、复用、避免干扰。<br />尽管像SASS、LESS这种预处理语言添加了很多用用的特性,但是他们依旧没有对改变CSS的混乱有太大的帮助。因此组织工作交给了像 BEM这样的方法,虽然比较有用,但是它完全是自选方案,不能被强制应用在语言或者工具层面。<br />他搭配<a href="http://www.js-code.com/tag/react" title="React" target="_blank">React</a>可能将模块化走向一个更高的高度,样式书写将直接依附在<a href="http://www.js-code.com/tag/jsx" title="JSX" target="_blank">JSX</a>上面,<a href="http://www.js-code.com/tag/html" title="HTML" target="_blank">HTML</a>、CSS、JS三者再次内聚。</p></blockquote> <h3 id="articleHeader1">基本</h3> <h4>安装</h4> <div class="widget-codetool" style="display:none;"> <div class="widget-codetool--inner"> <span class="selectCode code-tool" data-toggle="tooltip" data-placement="top" title="" data-original-title="全选"></span><br /> <span type="button" class="copyCode code-tool" data-toggle="tooltip" data-placement="top" data-clipboard-text="npm install --save styled-components" title="" data-original-title="复制"></span> </div> </p></div> <pre class="hljs sql"><code style="word-break: break-word; white-space: initial;">npm <span class="hljs-keyword"><a href="http://www.js-code.com/tag/in" title="浏览关于“in”的文章" target="_blank" class="tag_link">in</a>st<a href="http://www.js-code.com/tag/all" title="浏览关于“all”的文章" target="_blank" class="tag_link">all</a></span> <span class="hljs-comment">--save styled-components</span></code></pre> <p>除了npm安装使用模块化加载包之外,也支持<code>UMD</code>格式直接加载脚本文件。</p> <div class="widget-codetool" style="display:none;"> <div class="widget-codetool--inner"> <span class="selectCode code-tool" data-toggle="tooltip" data-placement="top" title="" data-original-title="全选"></span><br /> <span type="<a href="http://www.js-code.com/tag/button" title="button" target="_blank">button</a>" <a href="http://www.js-code.com/tag/class" title="class" target="_blank">class</a>="copyCode code-tool" data-toggle="tooltip" data-placement="<a href="http://www.js-code.com/tag/top" title="top" target="_blank">top</a>" data-clipboard-<a href="http://www.js-code.com/tag/text" title="text" target="_blank">text</a>="<script src=&quot;https://unpkg.com/styled-components/dist/styled-components.min.js&quot;></script>" title="" data-original-title="复制"></span> </div> </p></div> <pre class="hljs xml"><code style="word-break: break-word; white-space: initial;"><span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"https://unpkg.com/styled-components/dist/styled-components.min.js"</span>&gt;</span><span class="undefined"></span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span></code></pre> <h4>入门</h4> <p><code>styled-components</code>使用标签模板来对组件进行样式化。</p> <p>它移除了组件和样式之间的映射。这意味着,当你定义你的样式时,你实际上创造了一个正常的<a href="http://www.js-code.com/tag/react%e7%bb%84%e4%bb%b6" title="React组件" target="_blank">React组件</a>,你的样式也附在它上面。</p> <p>这个例子创建了两个简单的组件,一个容器和一个标题,并附加了一些样式。</p> <div class="widget-codetool" style="display:none;"> <div class="widget-codetool--inner"> <span class="selectCode code-tool" data-toggle="tooltip" data-placement="top" title="" data-original-title="全选"></span><br /> <span type="<a href="http://www.js-code.com/tag/button" title="button" target="_blank">button</a>" <a href="http://www.js-code.com/tag/class" title="class" target="_blank">class</a>="copyCode code-tool" data-toggle="tooltip" data-placement="<a href="http://www.js-code.com/tag/top" title="top" target="_blank">top</a>" data-clipboard-<a href="http://www.js-code.com/tag/text" title="text" target="_blank">text</a>="// Create a Title component that'll render an </p> <h1> tag with some styles<br /> <a href="http://www.js-code.com/tag/const" title="const" target="_blank">const</a> Title = styled.h1`<br /> font-size: 1.5em;<br /> <a href="http://www.js-code.com/tag/text" title="浏览关于“text”的文章" target="_blank" class="tag_link">text</a>-align: center;<br /> color: palevio<a href="http://www.js-code.com/tag/let" title="let" target="_blank">let</a>red;<br /> `;</p> <p>// Create a Wrapper component that'll render a </p> <section> tag with some styles<br /> <a href="http://www.js-code.com/tag/const" title="const" target="_blank">const</a> Wrapper = styled.section`<br /> padd<a href="http://www.js-code.com/tag/in" title="in" target="_blank">in</a>g: 4em;<br /> background: papayawhip;<br /> `;</p> <p>// Use Title and Wrapper like any other <a href="http://www.js-code.com/tag/react" title="React" target="_blank">React</a> component – except they're styled!<br /> render(<br /> <Wrapper><br /> <Title><br /> Hello World, <a href="http://www.js-code.com/tag/this" title="this" target="_blank">this</a> is my first styled component!<br /> </Title><br /> </Wrapper><br /> );" title="" data-original-title="复制"></span> </div> </p></div> <pre class="hljs javascript"><code><span class="hljs-comment">// Create a Title component that'll render an &lt;h1&gt; tag with some styles</span> <span class="hljs-keyword"><a href="http://www.js-code.com/tag/const" title="浏览关于“const”的文章" target="_blank" class="tag_link">const</a></span> Title = styled.h1<span class="hljs-string">` font-size: 1.5em; text-align: center; color: palevio<a href="http://www.js-code.com/tag/let" title="浏览关于“let”的文章" target="_blank" class="tag_link">let</a>red; `</span>; <span class="hljs-comment">// Create a Wrapper component that'll render a &lt;section&gt; tag with some styles</span> <span class="hljs-keyword">const</span> Wrapper = styled.section<span class="hljs-string">` padding: 4em; background: papayawhip; `</span>; <span class="hljs-comment">// Use Title and Wrapper like any other <a href="http://www.js-code.com/tag/react" title="浏览关于“React”的文章" target="_blank" class="tag_link">React</a> component – except they're styled!</span> render( <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Wrapper</span>&gt;</span> <span class="hljs-tag">&lt;<span class="hljs-name">Title</span>&gt;</span> Hello World, <a href="http://www.js-code.com/tag/this" title="浏览关于“this”的文章" target="_blank" class="tag_link">this</a> is my first styled component! <span class="hljs-tag">&lt;/<span class="hljs-name">Title</span>&gt;</span> <span class="hljs-tag">&lt;/<span class="hljs-name">Wrapper</span>&gt;</span></span> );</code></pre> <blockquote><p>注意<br />CSS规则会自动添加浏览器厂商前缀,我们不必考虑它。</p></blockquote> <h4>透传props</h4> <p><code>styled-components</code>会透传所有的props属性。</p> <div class="widget-codetool" style="display:none;"> <div class="widget-codetool--inner"> <span class="selectCode code-tool" data-toggle="tooltip" data-placement="top" title="" data-original-title="全选"></span><br /> <span type="<a href="http://www.js-code.com/tag/button" title="浏览关于“button”的文章" target="_blank" class="tag_link">button</a>" class="copyCode code-tool" data-toggle="tooltip" data-placement="<a href="http://www.js-code.com/tag/top" title="浏览关于“top”的文章" target="_blank" class="tag_link">top</a>" data-clipboard-text="// Create an Input component that'll render an <input> tag with some styles<br /> <a href="http://www.js-code.com/tag/const" title="const" target="_blank">const</a> Input = styled.<a href="http://www.js-code.com/tag/in" title="in" target="_blank">in</a>put`<br /> padding: 0.5em;<br /> margin: 0.5em;<br /> color: palevio<a href="http://www.js-code.com/tag/let" title="let" target="_blank">let</a>red;<br /> background: papayawhip;<br /> border: none;<br /> border-radius: 3px;<br /> `;</p> <p>// Render a styled text input with a placeholder of &quot;@mxstbr&quot;, and one with a value of &quot;@geelen&quot;<br /> render(</p> <div> <Input placeholder=&quot;@mxstbr&quot; type=&quot;text&quot; /><br /> <Input value=&quot;@geelen&quot; type=&quot;text&quot; /> </div> <p>);" title="" data-original-title="复制"></span> </div> </p></div> <pre class="hljs scala"><code><span class="hljs-comment">// Create an Input component that'll render an &lt;input&gt; tag with some styles</span> const <span class="hljs-type">Input</span> = styled.input` padding: <span class="hljs-number">0.5</span>em; margin: <span class="hljs-number">0.5</span>em; color: palevioletred; background: papayawhip; border: none; border-radius: <span class="hljs-number">3</span>px; `; <span class="hljs-comment">// Render a styled text input with a placeholder of "@mxstbr", and one with a value of "@geelen"</span> render( &lt;<a href="http://www.js-code.com/tag/div" title="浏览关于“div”的文章" target="_blank" class="tag_link">div</a>&gt; &lt;<span class="hljs-type">Input</span> placeholder=<span class="hljs-string">"@mxstbr"</span> <span class="hljs-class"><span class="hljs-keyword">type</span></span>=<span class="hljs-string">"text"</span> /&gt; &lt;<span class="hljs-type">Input</span> value=<span class="hljs-string">"@geelen"</span> <span class="hljs-class"><span class="hljs-keyword">type</span></span>=<span class="hljs-string">"text"</span> /&gt; &lt;/div&gt; );</code></pre> <h4>基于props做样式判断</h4> <p>模板标签的函数插值能拿到样式组件的props,可以据此调整我们的样式规则。</p> <div class="widget-codetool" style="display:none;"> <div class="widget-codetool--inner"> <span class="selectCode code-tool" data-toggle="tooltip" data-placement="top" title="" data-original-title="全选"></span><br /> <span type="button" class="copyCode code-tool" data-toggle="tooltip" data-placement="top" data-clipboard-text="const Button = styled.button` /* Adapt the colours based on primary prop */ background: ${props => props.primary ? 'palevioletred' : 'white'};<br /> color: ${props => props.primary ? 'white' : 'palevio<a href="http://www.js-code.com/tag/let" title="let" target="_blank">let</a>red'};</p> <p> font-size: 1em;<br /> margin: 1em;<br /> padding: 0.25em 1em;<br /> border: 2px solid palevio<a href="http://www.js-code.com/tag/let" title="let" target="_blank">let</a>red;<br /> border-radius: 3px;<br /> `;</p> <p>render(</p> <div> <Button>Normal</Button><br /> <Button primary>Primary</Button> </div> <p>);" title="" data-original-title="复制"></span> </div> </p></div> <pre class="hljs javascript"><code><span class="hljs-keyword">const</span> Button = styled.button<span class="hljs-string">` /* Adapt the colours based on primary prop */ background: <span class="hljs-subst">${props =&gt; props.primary ? <span class="hljs-string">'palevioletred'</span> : <span class="hljs-string">'white'</span>}</span>; color: <span class="hljs-subst">${props =&gt; props.primary ? <span class="hljs-string">'white'</span> : <span class="hljs-string">'palevioletred'</span>}</span>; font-size: 1em; margin: 1em; padding: 0.25em 1em; border: 2px solid palevioletred; border-radius: 3px; `</span>; render( <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span> <span class="hljs-tag">&lt;<span class="hljs-name">Button</span>&gt;</span>Normal<span class="hljs-tag">&lt;/<span class="hljs-name">Button</span>&gt;</span> <span class="hljs-tag">&lt;<span class="hljs-name">Button</span> <span class="hljs-attr">primary</span>&gt;</span>Primary<span class="hljs-tag">&lt;/<span class="hljs-name">Button</span>&gt;</span> <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span> );</code></pre> <h4>样式化任意组件</h4> <div class="widget-codetool" style="display:none;"> <div class="widget-codetool--inner"> <span class="selectCode code-tool" data-toggle="tooltip" data-placement="top" title="" data-original-title="全选"></span><br /> <span type="button" class="copyCode code-tool" data-toggle="tooltip" data-placement="top" data-clipboard-text="// This could be react-router's Link for example const Link = ({ className, children }) => (<br /> <a className={className}><br /> {children}<br /> </a><br /> )</p> <p><a href="http://www.js-code.com/tag/const" title="const" target="_blank">const</a> StyledLink = styled(Link)`<br /> color: palevioletred;<br /> font-weight: bold;<br /> `;</p> <p>render(</p> <div> <Link>Unstyled, boring Link</Link><br /> <br /> <StyledLink>Styled, exciting Link</StyledLink> </div> <p>);" title="" data-original-title="复制"></span> </div> </p></div> <pre class="hljs javascript"><code><span class="hljs-comment">// This could be react-router's Link <a href="http://www.js-code.com/tag/for" title="浏览关于“for”的文章" target="_blank" class="tag_link">for</a> example</span> <span class="hljs-keyword">const</span> Link = <span class="hljs-function">(<span class="hljs-params">{ className, children }</span>) =&gt;</span> ( <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">className</span>=<span class="hljs-string">{className}</span>&gt;</span> {children} <span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span></span> ) <span class="hljs-keyword">const</span> StyledLink = styled(Link)<span class="hljs-string">` color: palevioletred; font-weight: bold; `</span>; render( <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span> <span class="hljs-tag">&lt;<span class="hljs-name">Link</span>&gt;</span>Unstyled, boring Link<span class="hljs-tag">&lt;/<span class="hljs-name">Link</span>&gt;</span> <span class="hljs-tag">&lt;<span class="hljs-name">br</span> /&gt;</span> <span class="hljs-tag">&lt;<span class="hljs-name">StyledLink</span>&gt;</span>Styled, exciting Link<span class="hljs-tag">&lt;/<span class="hljs-name">StyledLink</span>&gt;</span> <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span> );</code></pre> <h4>扩展样式</h4> <p>我们有时候需要在我们的样式组件上做一点扩展,添加一些额外的样式:<br />需要注意的是<code>.extend</code>在对样式组件有效,如果是其他的<a href="http://www.js-code.com/tag/react%e7%bb%84%e4%bb%b6" title="React组件" target="_blank">React组件</a>,需要用<code>styled</code>样式化一下。</p> <div class="widget-codetool" style="display:none;"> <div class="widget-codetool--inner"> <span class="selectCode code-tool" data-toggle="tooltip" data-placement="top" title="" data-original-title="全选"></span><br /> <span type="button" class="copyCode code-tool" data-toggle="tooltip" data-placement="top" data-clipboard-text="// The Button from the last section without the <a href="http://www.js-code.com/tag/int" title="int" target="_blank">int</a>erpolations<br /> const Button = styled.button`<br /> color: palevioletred;<br /> font-size: 1em;<br /> margin: 1em;<br /> padding: 0.25em 1em;<br /> border: 2px solid palevioletred;<br /> border-radius: 3px;<br /> `;</p> <p>// We're extending Button with some extra styles<br /> const TomatoButton = Button.extend`<br /> color: tomato;<br /> border-color: tomato;<br /> `;</p> <p>render(</p> <div> <Button>Normal Button</Button><br /> <TomatoButton>Tomato Button</TomatoButton> </div> <p>);" title="" data-original-title="复制"></span> </div> </p></div> <pre class="hljs javascript"><code><span class="hljs-comment">// The Button from the last section without the <a href="http://www.js-code.com/tag/int" title="浏览关于“int”的文章" target="_blank" class="tag_link">int</a>erpolations</span> <span class="hljs-keyword">const</span> Button = styled.button<span class="hljs-string">` color: palevioletred; font-size: 1em; margin: 1em; padding: 0.25em 1em; border: 2px solid palevioletred; border-radius: 3px; `</span>; <span class="hljs-comment">// We're extending Button with some extra styles</span> <span class="hljs-keyword">const</span> TomatoButton = Button.extend<span class="hljs-string">` color: tomato; border-color: tomato; `</span>; render( <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span> <span class="hljs-tag">&lt;<span class="hljs-name">Button</span>&gt;</span>Normal Button<span class="hljs-tag">&lt;/<span class="hljs-name">Button</span>&gt;</span> <span class="hljs-tag">&lt;<span class="hljs-name">TomatoButton</span>&gt;</span>Tomato Button<span class="hljs-tag">&lt;/<span class="hljs-name">TomatoButton</span>&gt;</span> <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span> );</code></pre> <p>在极少特殊情况下,我们可能需要更改样式组件的标签类型。我们有一个特别的<a href="http://www.js-code.com/tag/api" title="API" target="_blank">API</a>,<code>withComponent</code>可以扩展样式和替换标签:</p> <div class="widget-codetool" style="display:none;"> <div class="widget-codetool--inner"> <span class="selectCode code-tool" data-toggle="tooltip" data-placement="top" title="" data-original-title="全选"></span><br /> <span type="button" class="copyCode code-tool" data-toggle="tooltip" data-placement="top" data-clipboard-text="const Button = styled.button` display: inline-block; color: palevioletred; font-size: 1em; margin: 1em; padding: 0.25em 1em; border: 2px solid palevioletred; border-radius: 3px; `; // We're replacing the <button> tag with an <a> tag, but reuse <a href="http://www.js-code.com/tag/all" title="all" target="_blank">all</a> the same styles<br /> const Link = Button.withComponent('a')</p> <p>// Use .withComponent together with .extend to both change the tag and use additional styles<br /> const TomatoLink = Link.extend`<br /> color: tomato;<br /> border-color: tomato;<br /> `;</p> <p>render(</p> <div> <Button>Normal Button</Button><br /> <Link>Normal Link</Link><br /> <TomatoLink>Tomato Link</TomatoLink> </div> <p>);" title="" data-original-title="复制"></span> </div> </p></div> <pre class="hljs javascript"><code><span class="hljs-keyword">const</span> Button = styled.button<span class="hljs-string">` display: inline-block; color: palevioletred; font-size: 1em; margin: 1em; padding: 0.25em 1em; border: 2px solid palevioletred; border-radius: 3px; `</span>; <span class="hljs-comment">// We're replacing the &lt;button&gt; tag with an &lt;a&gt; tag, but reuse all the same styles</span> <span class="hljs-keyword">const</span> Link = Button.withComponent(<span class="hljs-string">'a'</span>) <span class="hljs-comment">// Use .withComponent together with .extend to both change the tag and use additional styles</span> <span class="hljs-keyword">const</span> TomatoLink = Link.extend<span class="hljs-string">` color: tomato; border-color: tomato; `</span>; render( <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span> <span class="hljs-tag">&lt;<span class="hljs-name">Button</span>&gt;</span>Normal Button<span class="hljs-tag">&lt;/<span class="hljs-name">Button</span>&gt;</span> <span class="hljs-tag">&lt;<span class="hljs-name">Link</span>&gt;</span>Normal Link<span class="hljs-tag">&lt;/<span class="hljs-name">Link</span>&gt;</span> <span class="hljs-tag">&lt;<span class="hljs-name">TomatoLink</span>&gt;</span>Tomato Link<span class="hljs-tag">&lt;/<span class="hljs-name">TomatoLink</span>&gt;</span> <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span> );</code></pre> <h4>添加attr</h4> <p>我们可以使用<code>attrs</code><a href="http://www.js-code.com/tag/api" title="API" target="_blank">API</a>来为样式组件添加一些attr属性,它们也可以通过标签模板插值函数拿到props传值。</p> <div class="widget-codetool" style="display:none;"> <div class="widget-codetool--inner"> <span class="selectCode code-tool" data-toggle="tooltip" data-placement="top" title="" data-original-title="全选"></span><br /> <span type="button" class="copyCode code-tool" data-toggle="tooltip" data-placement="top" data-clipboard-text="const Input = styled.input.attrs({ // we can define static props type: 'password', // or we can define dynamic ones margin: props => props.size || '1em',<br /> padding: props => props.size || '1em'<br /> })`<br /> color: palevioletred;<br /> font-size: 1em;<br /> border: 2px solid palevioletred;<br /> border-radius: 3px;</p> <p> /* here we use the dynamically computed props */<br /> margin: ${props => props.margin};<br /> padding: ${props => props.padding};<br /> `;</p> <p>render(</p> <div> <Input placeholder=&quot;A small text input&quot; size=&quot;1em&quot; /><br /> <br /> <Input placeholder=&quot;A bigger text input&quot; size=&quot;2em&quot; /> </div> <p>);" title="" data-original-title="复制"></span> </div> </p></div> <pre class="hljs php"><code><span class="hljs-keyword">const</span> Input = styled.input.attrs({ <span class="hljs-comment">// we can define <a href="http://www.js-code.com/tag/static" title="浏览关于“static”的文章" target="_blank" class="tag_link">static</a> props</span> type: <span class="hljs-string">'<a href="http://www.js-code.com/tag/password" title="浏览关于“password”的文章" target="_blank" class="tag_link">password</a>'</span>, <span class="hljs-comment">// or we can define dynamic ones</span> margin: props =&gt; props.size || <span class="hljs-string">'1em'</span>, padding: props =&gt; props.size || <span class="hljs-string">'1em'</span> })` color: palevioletred; font-size: <span class="hljs-number">1</span>em; border: <span class="hljs-number">2</span>px solid palevioletred; border-radius: <span class="hljs-number">3</span>px; <span class="hljs-comment">/* here we use the dynamically computed props */</span> margin: ${props =&gt; props.margin}; padding: ${props =&gt; props.padding}; `; render( &lt;div&gt; &lt;Input placeholder=<span class="hljs-string">"A small text input"</span> size=<span class="hljs-string">"1em"</span> /&gt; &lt;br /&gt; &lt;Input placeholder=<span class="hljs-string">"A bigger text input"</span> size=<span class="hljs-string">"2em"</span> /&gt; &lt;/div&gt; );</code></pre> <h4>动画</h4> <p>带有@key<a href="http://www.js-code.com/tag/frame" title="frame" target="_blank">frame</a>s的CSS animations,一般来说会产生复用。<code>styled-components</code>暴露了一个<code>key<a href="http://www.js-code.com/tag/frames" title="frames" target="_blank">frames</a></code>的<a href="http://www.js-code.com/tag/api" title="浏览关于“API”的文章" target="_blank" class="tag_link">API</a>,我们使用它产生一个可以复用的变量。这样,我们在书写css样式的时候使用JavaScript的功能,为CSS附能,并且避免了名称冲突。</p> <div class="widget-codetool" style="display:none;"> <div class="widget-codetool--inner"> <span class="selectCode code-tool" data-toggle="tooltip" data-placement="top" title="" data-original-title="全选"></span><br /> <span type="button" class="copyCode code-tool" data-toggle="tooltip" data-placement="top" data-clipboard-text="// key<a href="http://www.js-code.com/tag/frame" title="frame" target="_blank">frame</a>s <a href="http://www.js-code.com/tag/return" title="return" target="_blank">return</a>s a unique <a href="http://www.js-code.com/tag/name" title="name" target="_blank">name</a> based on a hash of the contents of the key<a href="http://www.js-code.com/tag/frames" title="frames" target="_blank">frames</a><br /> const rotate360 = key<a href="http://www.js-code.com/tag/frames" title="浏览关于“frames”的文章" target="_blank" class="tag_link">frames</a>`<br /> from {<br /> trans<a href="http://www.js-code.com/tag/for" title="for" target="_blank">for</a>m: rotate(0deg);<br /> }</p> <p> to {<br /> trans<a href="http://www.js-code.com/tag/form" title="form" target="_blank">form</a>: rotate(360deg);<br /> }<br /> `;</p> <p>// Here we create a component that will rotate everything we pass in over two seconds<br /> const Rotate = styled.<a href="http://www.js-code.com/tag/div" title="div" target="_blank">div</a>`<br /> display: inline-block;<br /> animation: ${rotate360} 2s linear infinite;<br /> padding: 2rem 1rem;<br /> font-size: 1.2rem;<br /> `;</p> <p>render(<br /> <Rotate>&amp;lt; ???? &amp;gt;</Rotate><br /> );" title="" data-original-title="复制"></span> </div> </p></div> <pre class="hljs javascript"><code><span class="hljs-comment">// key<a href="http://www.js-code.com/tag/frame" title="浏览关于“frame”的文章" target="_blank" class="tag_link">frame</a>s <a href="http://www.js-code.com/tag/return" title="浏览关于“return”的文章" target="_blank" class="tag_link">return</a>s a unique <a href="http://www.js-code.com/tag/name" title="浏览关于“name”的文章" target="_blank" class="tag_link">name</a> based on a hash of the contents of the keyframes</span> <span class="hljs-keyword">const</span> rotate360 = keyframes<span class="hljs-string">` from { trans<a href="http://www.js-code.com/tag/form" title="浏览关于“form”的文章" target="_blank" class="tag_link">form</a>: rotate(0deg); } to { transform: rotate(360deg); } `</span>; <span class="hljs-comment">// Here we create a component that will rotate everything we pass in over two seconds</span> <span class="hljs-keyword">const</span> Rotate = styled.div<span class="hljs-string">` display: inline-block; animation: <span class="hljs-subst">${rotate360}</span> 2s linear infinite; padding: 2rem 1rem; font-size: 1.2rem; `</span>; render( <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Rotate</span>&gt;</span>&amp;lt; ???? &amp;gt;<span class="hljs-tag">&lt;/<span class="hljs-name">Rotate</span>&gt;</span></span> );</code></pre> <h4>支持 React Native</h4> <h3 id="articleHeader2">高级特性</h3> <h4>Theming</h4> <p><code>styled-components</code>暴露了一个<code>&lt;ThemeProvider&gt;</code>容器组件,提供了设置默认主题样式的功能,他类似于<code>react-rudux</code>的顶层组件<code>Provider</code>,通过<code>context</code>实现了从顶层到底层所有样式组件的默认主题共用。</p> <div class="widget-codetool" style="display:none;"> <div class="widget-codetool--inner"> <span class="selectCode code-tool" data-toggle="tooltip" data-placement="top" title="" data-original-title="全选"></span><br /> <span type="button" class="copyCode code-tool" data-toggle="tooltip" data-placement="top" data-clipboard-text="const Button = styled.button` font-size: 1em; margin: 1em; padding: 0.25em 1em; border-radius: 3px; /* Color the border and text with theme.main */ color: ${props => props.theme.main};<br /> border: 2px solid ${props => props.theme.main};<br /> `;</p> <p>Button.<a href="http://www.js-code.com/tag/default" title="default" target="_blank">default</a><a href="http://www.js-code.com/tag/prop" title="Prop" target="_blank">Prop</a>s = {<br /> theme: {<br /> main: 'palevioletred'<br /> }<br /> }<br /> // Define what props.theme will look like<br /> const theme = {<br /> main: 'mediumseagreen'<br /> };</p> <p>render(</p> <div> <Button>Normal</Button><br /> <ThemeProvider theme={theme}><br /> <Button>Themed</Button><br /> </ThemeProvider> </div> <p>);" title="" data-original-title="复制"></span> </div> </p></div> <pre class="hljs javascript"><code><span class="hljs-keyword">const</span> Button = styled.button<span class="hljs-string">` font-size: 1em; margin: 1em; padding: 0.25em 1em; border-radius: 3px; /* Color the border and text with theme.main */ color: <span class="hljs-subst">${props =&gt; props.theme.main}</span>; border: 2px solid <span class="hljs-subst">${props =&gt; props.theme.main}</span>; `</span>; Button.<a href="http://www.js-code.com/tag/default" title="浏览关于“default”的文章" target="_blank" class="tag_link">default</a><a href="http://www.js-code.com/tag/prop" title="浏览关于“Prop”的文章" target="_blank" class="tag_link">Prop</a>s = { <span class="hljs-attr">theme</span>: { <span class="hljs-attr">main</span>: <span class="hljs-string">'palevioletred'</span> } } <span class="hljs-comment">// Define what props.theme will look like</span> <span class="hljs-keyword">const</span> theme = { <span class="hljs-attr">main</span>: <span class="hljs-string">'mediumseagreen'</span> }; render( <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span> <span class="hljs-tag">&lt;<span class="hljs-name">Button</span>&gt;</span>Normal<span class="hljs-tag">&lt;/<span class="hljs-name">Button</span>&gt;</span> <span class="hljs-tag">&lt;<span class="hljs-name">ThemeProvider</span> <span class="hljs-attr">theme</span>=<span class="hljs-string">{theme}</span>&gt;</span> <span class="hljs-tag">&lt;<span class="hljs-name">Button</span>&gt;</span>Themed<span class="hljs-tag">&lt;/<span class="hljs-name">Button</span>&gt;</span> <span class="hljs-tag">&lt;/<span class="hljs-name">ThemeProvider</span>&gt;</span> <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span> );</code></pre> <h4>Refs</h4> <p>通常我们在给一个非原生样式组件添加<code>ref</code>属性的时候,其指向都是该组件实例的索引,我们通过用<code>innerRef</code>可以直接拿到里面的<code><a href="http://www.js-code.com/tag/dom" title="DOM" target="_blank">DOM</a></code>节点。</p> <div class="widget-codetool" style="display:none;"> <div class="widget-codetool--inner"> <span class="selectCode code-tool" data-toggle="tooltip" data-placement="top" title="" data-original-title="全选"></span><br /> <span type="button" class="copyCode code-tool" data-toggle="tooltip" data-placement="top" data-clipboard-text="const AutoFocusInput = styled.input` background: papayawhip; border: none; `; class Form <a href="http://www.js-code.com/tag/extends" title="extends" target="_blank">extends</a> React.Component {<br /> render() {<br /> <a href="http://www.js-code.com/tag/return" title="return" target="_blank">return</a> (<br /> <AutoFocusInput placeholder=&quot;Hover here...&quot; innerRef={x => { this.input = x }}<br /> onMouseEnter={() => this.input.focus()}<br /> /><br /> );<br /> }<br /> }" title="" data-original-title="复制"></span> </div> </p></div> <pre class="hljs scala"><code>const <span class="hljs-type">AutoFocusInput</span> = styled.input` background: papayawhip; border: none; `; <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Form</span> <span class="hljs-keyword"><a href="http://www.js-code.com/tag/extends" title="浏览关于“extends”的文章" target="_blank" class="tag_link">extends</a></span> <span class="hljs-title">React</span>.<span class="hljs-title">Component</span> </span>{ render() { <span class="hljs-keyword">return</span> ( &lt;<span class="hljs-type">AutoFocusInput</span> placeholder=<span class="hljs-string">"Hover here..."</span> innerRef={x =&gt; { <span class="hljs-keyword">this</span>.input = x }} onMouseEnter={() =&gt; <span class="hljs-keyword">this</span>.input.<a href="http://www.js-code.com/tag/focus" title="浏览关于“focus”的文章" target="_blank" class="tag_link">focus</a>()} /&gt; ); } }</code></pre> <h4>Security</h4> <p>因为<code>styled-components</code>允许我们使用任意输入作为<code>CSS</code>属性值,一旦意识到这一点,我们马上明白要对输入做安全性校验了,因为使用用户外部的输入样式可以导致用户的浏览器被CSS注入攻击。CSS注入攻击可能不明显,但是我们还是得小心一点,某些IE浏览器版本甚至允许在URL声明中执行任意的JS。</p> <p>这个例子告诉我们外部的输入甚至可能在CSS内调用一个API网络请求。</p> <div class="widget-codetool" style="display:none;"> <div class="widget-codetool--inner"> <span class="selectCode code-tool" data-toggle="tooltip" data-placement="top" title="" data-original-title="全选"></span><br /> <span type="button" class="copyCode code-tool" data-toggle="tooltip" data-placement="top" data-clipboard-text="// Oh no! The user has given us a bad URL! const userInput = '/api/withdraw-funds'; const ArbitraryComponent = styled.div` background: url(${userInput}); /* More styles here... */ `;" title="" data-original-title="复制"></span> </div> </p></div> <pre class="hljs typescript"><code><span class="hljs-comment">// Oh no! The user has given us a bad URL!</span> <span class="hljs-keyword">const</span> userInput = <span class="hljs-string">'/api/withdraw-funds'</span>; <span class="hljs-keyword">const</span> ArbitraryComponent = styled.div<span class="hljs-string">` background: url(<span class="hljs-subst">${userInput}</span>); /* More styles here... */ `</span>;</code></pre> <p><a href="https://developer.mozilla.org/en-US/docs/Web/API/CSS/escape" rel="nofollow noreferrer" target="_blank"><code>CSS.<a href="http://www.js-code.com/tag/escape" title="escape" target="_blank">escape</a></code></a>这个未来API标准可净化JS中的CSS的问题。但是浏览器兼容性目前还不是太好,所以我们建议在项目中使用<a href="https://github.com/mathiasbynens/CSS.escape" rel="nofollow noreferrer" target="_blank"><code>polyfill by <a href="http://www.js-code.com/tag/Math" title="Math" target="_blank">Math</a>ias Bynens</code></a>。</p> <h4>CSS共存</h4> <p>如果我们打算把<code>styled-components</code>和现有的<code>css</code>共存的话,我们需要注意两个实现的细节问题:</p> <p><code>styled-components</code>也会生成真实的样式表,并通过<code>className</code>属性链接生成的样式表内容。在JS运行时,他会生成一份真实的style节点插入到<a href="http://www.js-code.com/tag/do" title="do" target="_blank">do</a>cument的head内。</p> <p>注意的一个小地方:</p> <div class="widget-codetool" style="display:none;"> <div class="widget-codetool--inner"> <span class="selectCode code-tool" data-toggle="tooltip" data-placement="top" title="" data-original-title="全选"></span><br /> <span type="button" class="copyCode code-tool" data-toggle="tooltip" data-placement="top" data-clipboard-text="// MyComponent.js const MyComponent = styled.<a href="http://www.js-code.com/tag/div" title="div" target="_blank">div</a>`background-color: green;`;</p> <p>// my-component.css<br /> .red-bg {<br /> background-color: red;<br /> }</p> <p>// For some reason <a href="http://www.js-code.com/tag/this" title="this" target="_blank">this</a> component still has a green background,<br /> // even though you're <a href="http://www.js-code.com/tag/try" title="try" target="_blank">try</a>ing to override it with the &quot;red-bg&quot; class!<br /> <MyComponent className=&quot;red-bg&quot; ></span>" title="" data-original-title="复制"></span> </div> </p></div> <pre class="hljs typescript"><code><span class="hljs-comment">// MyComponent.js</span> <span class="hljs-keyword">const</span> MyComponent = styled.div<span class="hljs-string">`background-color: green;`</span>; <span class="hljs-comment">// my-component.css</span> .red-bg { background-color: red; } <span class="hljs-comment">// For some reason this component still has a green background,</span> <span class="hljs-comment">// even though you're <a href="http://www.js-code.com/tag/try" title="浏览关于“try”的文章" target="_blank" class="tag_link">try</a>ing to override it with the "red-bg" class!</span> &lt;MyComponent className=<span class="hljs-string">"red-bg"</span> /&gt;</code></pre> <p>我们<code>styled-components</code>生成的style样式表一般是在head头部的最底下,同等CSS优先级条件下是会覆盖默认前者css文件的样式的。这个插入顺序使用webpack来调整是比较难得。所以,我们一般都这样通过调整css优先级来改变显示:</p> <div class="widget-codetool" style="display:none;"> <div class="widget-codetool--inner"> <span class="selectCode code-tool" data-toggle="tooltip" data-placement="top" title="" data-original-title="全选"></span><br /> <span type="button" class="copyCode code-tool" data-toggle="tooltip" data-placement="top" data-clipboard-text="/* my-component.css */ .red-bg.red-bg { background-color: red; }" title="" data-original-title="复制"></span> </div> </p></div> <pre class="hljs css"><code><span class="hljs-comment">/* my-component.css */</span> <span class="hljs-selector-class">.red-bg</span><span class="hljs-selector-class">.red-bg</span> { <span class="hljs-attribute">background-color</span>: red; }</code></pre> <h4>Media <a href="http://www.js-code.com/tag/template" title="Template" target="_blank">Template</a>s</h4> <p>媒体查询是开发响应式web应用不可或缺的存在,这是一个简单的例子:</p> <div class="widget-codetool" style="display:none;"> <div class="widget-codetool--inner"> <span class="selectCode code-tool" data-toggle="tooltip" data-placement="top" title="" data-original-title="全选"></span><br /> <span type="button" class="copyCode code-tool" data-toggle="tooltip" data-placement="top" data-clipboard-text="const Content = styled.div` background: papayawhip; height: 3em; width: 3em; @media (max-width: 700px) { background: palevioletred; } `; render( <Content ></span><br /> );" title="" data-original-title="复制"></span> </div> </p></div> <pre class="hljs properties"><code><span class="hljs-attr">const</span> <span class="hljs-string">Content = styled.div`</span> <span class="hljs-attr">background</span>: <span class="hljs-string">papayawhip;</span> <span class="hljs-attr">height</span>: <span class="hljs-string">3em;</span> <span class="hljs-attr">width</span>: <span class="hljs-string">3em;</span> <span class="hljs-meta">@media</span> <span class="hljs-string">(max-width: 700px) {</span> <span class="hljs-attr">background</span>: <span class="hljs-string">palevioletred;</span> <span class="hljs-attr">}</span> <span class="hljs-attr">`;</span> <span class="hljs-attr">render(</span> <span class="hljs-meta">&lt;Content</span> <span class="hljs-string">/&gt;</span> <span class="hljs-attr">);</span></code></pre> <p>因为媒体查询语句很长,并且经常在整个应用程序中重复使用,所以为此创建一些模板来复用是很有必要的。</p> <p>使用JS的功能特性,我们可以轻松定义一份可配置的语句,包装媒体查询和样式。</p> <div class="widget-codetool" style="display:none;"> <div class="widget-codetool--inner"> <span class="selectCode code-tool" data-toggle="tooltip" data-placement="top" title="" data-original-title="全选"></span><br /> <span type="button" class="copyCode code-tool" data-toggle="tooltip" data-placement="top" data-clipboard-text="const sizes = { desktop: 992, tablet: 768, phone: 376 } // Iterate through the sizes and create a media template const media = Object.keys(sizes).reduce((acc, label) => {<br /> acc[label] = (...args) => css`<br /> @media (max-width: ${sizes[label] / 16}em) {<br /> ${css(...args)}<br /> }<br /> `</p> <p> <a href="http://www.js-code.com/tag/return" title="return" target="_blank">return</a> acc<br /> }, {})</p> <p>const Content = styled.div`<br /> height: 3em;<br /> width: 3em;<br /> background: papayawhip;</p> <p> /* Now we have our methods on media and can use them instead of raw queries */<br /> ${media.desktop`background: <a href="http://www.js-code.com/tag/do" title="do" target="_blank">do</a>dgerblue;`}<br /> ${media.tablet`background: mediumseagreen;`}<br /> ${media.phone`background: palevioletred;`}<br /> `;</p> <p>render(<br /> <Content ></Content><br /> );" title="" data-original-title="复制"></span> </div> </p></div> <pre class="hljs typescript"><code><span class="hljs-keyword">const</span> sizes = { desktop: <span class="hljs-number">992</span>, tablet: <span class="hljs-number">768</span>, phone: <span class="hljs-number">376</span> } <span class="hljs-comment">// Iterate through the sizes and create a media template</span> <span class="hljs-keyword">const</span> media = <span class="hljs-built_in"><a href="http://www.js-code.com/tag/Object" title="浏览关于“Object”的文章" target="_blank" class="tag_link">Object</a></span>.keys(sizes).reduce(<span class="hljs-function">(<span class="hljs-params">acc, label</span>) =&gt;</span> { acc[label] = <span class="hljs-function">(<span class="hljs-params">...args</span>) =&gt;</span> css<span class="hljs-string">` @media (max-width: <span class="hljs-subst">${sizes[label] / 16}</span>em) { <span class="hljs-subst">${css(...args)}</span> } `</span> <span class="hljs-keyword">return</span> acc }, {}) <span class="hljs-keyword">const</span> Content = styled.div<span class="hljs-string">` height: 3em; width: 3em; background: papayawhip; /* Now we have our methods on media and can use them instead of raw queries */ <span class="hljs-subst">${media.desktop`background: <a href="http://www.js-code.com/tag/do" title="浏览关于“do”的文章" target="_blank" class="tag_link">do</a>dgerblue;`}</span> <span class="hljs-subst">${media.tablet`background: mediumseagreen;`}</span> <span class="hljs-subst">${media.phone`background: palevioletred;`}</span> `</span>; render( &lt;Content /&gt; );</code></pre> <p>这太cool了,不是吗?</p> <h4>Tagged <a href="http://www.js-code.com/tag/template" title="Template" target="_blank">Template</a> Literals</h4> <p>标签模板是ES6的一个新特性,这是我们<code>styled-components</code>创建样式组件的方式和规则。</p> <div class="widget-codetool" style="display:none;"> <div class="widget-codetool--inner"> <span class="selectCode code-tool" data-toggle="tooltip" data-placement="top" title="" data-original-title="全选"></span><br /> <span type="button" class="copyCode code-tool" data-toggle="tooltip" data-placement="top" data-clipboard-text="const aVar = 'good'; // These are equivalent: fn`this is a ${aVar} day`; fn([ 'this is a ', ' day' ], aVar);" title="" data-original-title="复制"></span> </div> </p></div> <pre class="hljs kotlin"><code><span class="hljs-keyword">const</span> aVar = <span class="hljs-string">'good'</span>; <span class="hljs-comment">// These are equivalent:</span> fn`<span class="hljs-keyword">this</span> <span class="hljs-keyword">is</span> a ${aVar} day`; fn([ <span class="hljs-string">'this is a '</span>, <span class="hljs-string">' day'</span> ], aVar);</code></pre> <p>这看起来有点麻烦,但是这意味着我们可以在<code>styled-components</code>生成样式组件中接受变量、函数、minxins,并将其变为纯css。</p> <p>这篇文章可以了解更多:<a href="https://mxstbr.blog/2016/11/styled-components-magic-explained/" rel="nofollow noreferrer" target="_blank">The magic behind ???? styled-components</a></p> <h4>Server Side Rendering</h4> <p><code>styled-components</code>很好地支持SSR。</p> <p>一个例子:</p> <div class="widget-codetool" style="display:none;"> <div class="widget-codetool--inner"> <span class="selectCode code-tool" data-toggle="tooltip" data-placement="top" title="" data-original-title="全选"></span><br /> <span type="button" class="copyCode code-tool" data-toggle="tooltip" data-placement="top" data-clipboard-text="<a href="http://www.js-code.com/tag/import" title="import" target="_blank">import</a> { renderTo<a href="http://www.js-code.com/tag/String" title="String" target="_blank">String</a> } from 'react-dom/server'<br /> <a href="http://www.js-code.com/tag/import" title="import" target="_blank">import</a> { ServerStyleSheet } from 'styled-components'</p> <p>const sheet = <a href="http://www.js-code.com/tag/new" title="new" target="_blank">new</a> ServerStyleSheet()<br /> const html = renderTo<a href="http://www.js-code.com/tag/String" title="String" target="_blank">String</a>(sheet.collectStyles(<YourApp ></span>))<br /> const styleTags = sheet.getStyleTags() // or sheet.getStyleElement()" title="" data-original-title="复制"></span> </div> </p></div> <pre class="hljs typescript"><code><span class="hljs-keyword">import</span> { renderTo<a href="http://www.js-code.com/tag/String" title="浏览关于“String”的文章" target="_blank" class="tag_link">String</a> } <span class="hljs-keyword">from</span> <span class="hljs-string">'react-dom/server'</span> <span class="hljs-keyword">import</span> { ServerStyleSheet } <span class="hljs-keyword">from</span> <span class="hljs-string">'styled-components'</span> <span class="hljs-keyword">const</span> sheet = <span class="hljs-keyword"><a href="http://www.js-code.com/tag/new" title="浏览关于“new”的文章" target="_blank" class="tag_link">new</a></span> ServerStyleSheet() <span class="hljs-keyword">const</span> html = renderToString(sheet.collectStyles(&lt;YourApp /&gt;)) <span class="hljs-keyword">const</span> styleTags = sheet.getStyleTags() <span class="hljs-comment">// or sheet.getStyleElement()</span></code></pre> <p>也可以这样组件化包裹,只要在客户端不这么使用:</p> <div class="widget-codetool" style="display:none;"> <div class="widget-codetool--inner"> <span class="selectCode code-tool" data-toggle="tooltip" data-placement="top" title="" data-original-title="全选"></span><br /> <span type="button" class="copyCode code-tool" data-toggle="tooltip" data-placement="top" data-clipboard-text="import { renderToString } from 'react-dom/server' import { ServerStyleSheet, StyleSheetManager } from 'styled-components' const sheet = <a href="http://www.js-code.com/tag/new" title="new" target="_blank">new</a> ServerStyleSheet()<br /> const html = renderToString(<br /> <StyleSheetManager sheet={sheet.instance}><br /> <YourApp ></YourApp><br /> </StyleSheetManager><br /> )</p> <p>const styleTags = sheet.getStyleTags() // or sheet.getStyleElement()" title="" data-original-title="复制"></span> </div> </p></div> <pre class="hljs javascript"><code><span class="hljs-keyword">import</span> { renderToString } <span class="hljs-keyword">from</span> <span class="hljs-string">'react-dom/server'</span> <span class="hljs-keyword">import</span> { ServerStyleSheet, StyleSheetManager } <span class="hljs-keyword">from</span> <span class="hljs-string">'styled-components'</span> <span class="hljs-keyword">const</span> sheet = <span class="hljs-keyword">new</span> ServerStyleSheet() <span class="hljs-keyword">const</span> html = renderToString( <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">StyleSheetManager</span> <span class="hljs-attr">sheet</span>=<span class="hljs-string">{sheet.instance}</span>&gt;</span> <span class="hljs-tag">&lt;<span class="hljs-name">YourApp</span> /&gt;</span> <span class="hljs-tag">&lt;/<span class="hljs-name">StyleSheetManager</span>&gt;</span></span> ) <span class="hljs-keyword">const</span> styleTags = sheet.getStyleTags() <span class="hljs-comment">// or sheet.getStyleElement()</span></code></pre> <p><code>sheet.getStyleTags()</code>返回一个style标签<a href="http://www.js-code.com/tag/%e6%95%b0%e7%bb%84" title="数组" target="_blank">数组</a>。具体<code>styled-components</code>关于SSR更深入的操作,不在这里继续讨论了,还可以告知他兼容<code>Next.js</code>关于<code>SSR</code>的解决方案。</p> <h4>Referring to other components</h4> <p><code>styled-components</code>提供了<code>component <a href="http://www.js-code.com/tag/select" title="select" target="_blank">select</a>or</code>组件选择器模式来代替我们以往对class名的依赖,解决得很干净。这下我们不必为命名和选择器冲突而苦恼了。</p> <div class="widget-codetool" style="display:none;"> <div class="widget-codetool--inner"> <span class="selectCode code-tool" data-toggle="tooltip" data-placement="top" title="" data-original-title="全选"></span><br /> <span type="button" class="copyCode code-tool" data-toggle="tooltip" data-placement="top" data-clipboard-text="const Link = styled.a` display: <a href="http://www.js-code.com/tag/flex" title="flex" target="_blank">flex</a>;<br /> align-items: center;<br /> padding: 5px 10px;<br /> background: papayawhip;<br /> color: palevioletred;<br /> `;</p> <p>const Icon = styled.svg`<br /> transition: fill 0.25s;<br /> width: 48px;<br /> height: 48px;</p> <p> ${Link}:hover &amp; {<br /> fill: rebeccapurple;<br /> }<br /> `;</p> <p>const Label = styled.span`<br /> display: <a href="http://www.js-code.com/tag/flex" title="flex" target="_blank">flex</a>;<br /> align-items: center;<br /> line-height: 1.2;</p> <p> &amp;::be<a href="http://www.js-code.com/tag/for" title="for" target="_blank">for</a>e {<br /> content: '&#x25c0;';<br /> margin: 0 10px;<br /> }<br /> `;</p> <p>render(<br /> <Link href=&quot;#&quot;><br /> <Icon viewBox=&quot;0 0 20 20&quot;> <path d=&quot;M10 15h8c1 0 2-1 2-2V3c0-1-1-2-2-2H2C1 1 0 2 0 3v10c0 1 1 2 2 2h4v4l4-4zM5 7h2v2H5V7zm4 0h2v2H9V7zm4 0h2v2h-2V7z&quot;></path> </Icon><br /> <Label>Hovering my <a href="http://www.js-code.com/tag/parent" title="parent" target="_blank">parent</a> changes my style!</Label><br /> </Link><br /> );" title="" data-original-title="复制"></span> </div> </p></div> <pre class="hljs javascript"><code><span class="hljs-keyword">const</span> Link = styled.a<span class="hljs-string">` display: <a href="http://www.js-code.com/tag/flex" title="浏览关于“flex”的文章" target="_blank" class="tag_link">flex</a>; align-items: center; padding: 5px 10px; background: papayawhip; color: palevioletred; `</span>; <span class="hljs-keyword">const</span> Icon = styled.svg<span class="hljs-string">` transition: fill 0.25s; width: 48px; height: 48px; <span class="hljs-subst">${Link}</span>:hover &amp; { fill: rebeccapurple; } `</span>; <span class="hljs-keyword">const</span> Label = styled.span<span class="hljs-string">` display: flex; align-items: center; line-height: 1.2; &amp;::before { content: '&#x25c0;'; margin: 0 10px; } `</span>; render( <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Link</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"#"</span>&gt;</span> <span class="hljs-tag">&lt;<span class="hljs-name">Icon</span> <span class="hljs-attr">viewBox</span>=<span class="hljs-string">"0 0 20 20"</span>&gt;</span> <span class="hljs-tag">&lt;<span class="hljs-name">path</span> <span class="hljs-attr">d</span>=<span class="hljs-string">"M10 15h8c1 0 2-1 2-2V3c0-1-1-2-2-2H2C1 1 0 2 0 3v10c0 1 1 2 2 2h4v4l4-4zM5 7h2v2H5V7zm4 0h2v2H9V7zm4 0h2v2h-2V7z"</span>/&gt;</span> <span class="hljs-tag">&lt;/<span class="hljs-name">Icon</span>&gt;</span> <span class="hljs-tag">&lt;<span class="hljs-name">Label</span>&gt;</span>Hovering my <a href="http://www.js-code.com/tag/parent" title="浏览关于“parent”的文章" target="_blank" class="tag_link">parent</a> changes my style!<span class="hljs-tag">&lt;/<span class="hljs-name">Label</span>&gt;</span> <span class="hljs-tag">&lt;/<span class="hljs-name">Link</span>&gt;</span> );</span></code></pre> <p>注意:</p> <div class="widget-codetool" style="display:none;"> <div class="widget-codetool--inner"> <span class="selectCode code-tool" data-toggle="tooltip" data-placement="top" title="" data-original-title="全选"></span><br /> <span type="button" class="copyCode code-tool" data-toggle="tooltip" data-placement="top" data-clipboard-text="class A <a href="http://www.js-code.com/tag/extends" title="extends" target="_blank">extends</a> React.Component {<br /> render() {<br /> <a href="http://www.js-code.com/tag/return" title="return" target="_blank">return</a> </p> <div ></span>;<br /> }<br /> }</p> <p>const B = styled.div`<br /> ${A} {<br /> }<br /> `;" title="" data-original-title="复制"></span> </div> </p></div> <pre class="hljs scala"><code><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">A</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">React</span>.<span class="hljs-title">Component</span> </span>{ render() { <span class="hljs-keyword">return</span> &lt;div /&gt;; } } const <span class="hljs-type">B</span> = styled.div` ${<span class="hljs-type">A</span>} { } `;</code></pre> <p>这个例子是不可以的,因为A继承ReactComponent,不是被styled构造过的。我们的组件选择器只支持在<code>Styled Components</code>创建的样式组件。</p> <div class="widget-codetool" style="display:none;"> <div class="widget-codetool--inner"> <span class="selectCode code-tool" data-toggle="tooltip" data-placement="top" title="" data-original-title="全选"></span><br /> <span type="button" class="copyCode code-tool" data-toggle="tooltip" data-placement="top" data-clipboard-text="class A extends React.Component { render() { return <div className={this.props.className} ></span>;<br /> }<br /> }</p> <p>const StyledA = styled(A)``;</p> <p>const B = styled.div`<br /> ${StyledA} {<br /> }<br /> `;" title="" data-original-title="复制"></span> </div> </p></div> <pre class="hljs scala"><code><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">A</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">React</span>.<span class="hljs-title">Component</span> </span>{ render() { <span class="hljs-keyword">return</span> &lt;div className={<span class="hljs-keyword">this</span>.props.className} /&gt;; } } const <span class="hljs-type">StyledA</span> = styled(<span class="hljs-type">A</span>)``; const <span class="hljs-type">B</span> = styled.div` ${<span class="hljs-type">StyledA</span>} { } `;</code></pre> <h3 id="articleHeader3">API文档</h3> <h4>基本</h4> <ul> <li>styled</li> <li>.attrs</li> <li>``字符模板</li> <li>ThemeProvider</li> </ul> <h4>助手</h4> <ul> <li>css</li> <li>keyframes</li> <li>injectGlobal</li> <li>isStyledComponent</li> <li>withTheme</li> </ul> <h4>支持CSS</h4> <p>在样式组件中,我们支持所有CSS加嵌套。因为我们生成一个真实的stylesheet而不是内联样式,所以CSS中的任何工作都在样式组件中工作!</p> <p>(&amp;)被我们所生成的、唯一的类名替换给样式组件,使其具有复杂的逻辑变得容易。</p> <h4>支持flow和typescript</h4> <h3 id="articleHeader4">更多工具</h3> <h4>Babel Plugin</h4> <h4>Test Utilities</h4> <p><a href="https://github.com/styled-components/jest-styled-components" rel="nofollow noreferrer" target="_blank">Jest Styled Components</a>,基于jest,可对<code>styled-components</code>做单元测试</p> <p><a href="https://github.com/styled-components/styled-components-website/tree/master/test" rel="nofollow noreferrer" target="_blank">demo</a></p> <h4>Stylel<a href="http://www.js-code.com/tag/int" title="int" target="_blank">int</a></h4> <p>使用stylelint 检查我们的<code>styled-components</code>样式书写规范。</p> <h4>Styled Theming 语法高亮显示</h4> <p>在模板文本中写入CSS时丢失的一个东西是语法高亮显示。我们正在努力在所有编辑器中实现正确的语法高亮显示。支持大部分编辑器包括Visual Studio Code、WebStorm。</p> <h3 id="articleHeader5">总结</h3> <p>下面简单总结一下 styled-components 在开发中的表现:</p> <ul> <li>提出了 container 和 components 的概念,移除了组件和样式之间的映射关系,符合关注度分离的模式;</li> <li>可以在样式定义中直接引用到 js 变量,共享变量,非常便利,利用js的特性为css附能,帅毙了!</li> <li>支持组件之间继承,方便代码复用,提升可维护性;</li> <li>兼容现有的 className 方式,升级无痛;</li> <li>这下写CSS也乐趣十足了。</li> <li>styled-components的最基本思想就是通过移除样式和组件之间的映射来执行最佳实践</li> <li>一个让styled-components很容易被接受的特性:当他被怀疑的时候,你同样可以使用你熟悉的方法去使用它!</li> </ul> <p>当然,styled-components 还有一些优秀的特性,比如服务端渲染和 React Native 的支持。</p> <hr> <hr> <h3 id="articleHeader6">题外:styled-components的魔法</h3> <p>如果你从来没看见过<code>styled-components</code>,下面是一个简单的样式组件的例子:</p> <div class="widget-codetool" style="display:none;"> <div class="widget-codetool--inner"> <span class="selectCode code-tool" data-toggle="tooltip" data-placement="top" title="" data-original-title="全选"></span><br /> <span type="button" class="copyCode code-tool" data-toggle="tooltip" data-placement="top" data-clipboard-text="const Button = styled.button` background-color: papayawhip; border-radius: 3px; color: palevioletred; `" title="" data-original-title="复制"></span> </div> </p></div> <pre class="hljs typescript"><code><span class="hljs-keyword">const</span> Button = styled.button<span class="hljs-string">` background-color: papayawhip; border-radius: 3px; color: palevioletred; `</span></code></pre> <p>现在可以像使用普通<a href="http://www.js-code.com/tag/react%e7%bb%84%e4%bb%b6" title="浏览关于“React组件”的文章" target="_blank" class="tag_link">React组件</a>一样渲染使用。</p> <div class="widget-codetool" style="display:none;"> <div class="widget-codetool--inner"> <span class="selectCode code-tool" data-toggle="tooltip" data-placement="top" title="" data-original-title="全选"></span><br /> <span type="button" class="copyCode code-tool" data-toggle="tooltip" data-placement="top" data-clipboard-text="<Button>Hi Dad!</Button>" title="" data-original-title="复制"></span> </div> </p></div> <pre class="hljs xml"><code style="word-break: break-word; white-space: initial;"><span class="hljs-tag">&lt;<span class="hljs-name">Button</span>&gt;</span>Hi Dad!<span class="hljs-tag">&lt;/<span class="hljs-name">Button</span>&gt;</span></code></pre> <p>那么,这是怎么工作的呢?这个过程中到底发生了什么魔法?</p> <h4>标签模板</h4> <p>实际上,<code> style.button</code>` `是JavaScript的新语法特性,属于ES6的标签模板功能。</p> <p>本质上,<code> styled.button</code>` <code>和</code>styled.button()`是一样的。他们的差异只在传递参数时就变得可见了。</p> <p>styled-components利用<a href="http://www.js-code.com/tag/%e6%a8%a1%e6%9d%bf%e5%ad%97%e7%ac%a6%e4%b8%b2" title="模板字符串" target="_blank">模板字符串</a>的用处在于可以给内部props赋值。</p> <div class="widget-codetool" style="display:none;"> <div class="widget-codetool--inner"> <span class="selectCode code-tool" data-toggle="tooltip" data-placement="top" title="" data-original-title="全选"></span><br /> <span type="button" class="copyCode code-tool" data-toggle="tooltip" data-placement="top" data-clipboard-text="const Button = styled.button` font-size: ${props => props.primary ? '2em' : '1em'};<br /> `<br /> // font-size: 2em;<br /> <Button primary ></Button>" title="" data-original-title="复制"></span> </div> </p></div> <pre class="hljs javascript"><code><span class="hljs-keyword">const</span> Button = styled.button<span class="hljs-string">` font-size: <span class="hljs-subst">${props =&gt; props.primary ? <span class="hljs-string">'2em'</span> : <span class="hljs-string">'1em'</span>}</span>; `</span> <span class="hljs-comment">// font-size: 2em;</span> &lt;Button primary /&gt;</code></pre> <p></code></p>

总结

以上是脚本宝典为你收集整理的

Styled-Components

全部内容,希望文章能够帮你解决

Styled-Components

所遇到的程序开发问题,欢迎加入QQ群277859234一起讨论学习。如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典网站推荐给程序员好友。 本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。

80%的人都看过