LoginSignup
43
23

More than 5 years have passed since last update.

styled-components v4の新機能まとめ

Last updated at Posted at 2018-10-16

先日、styled-components v4がリリースされました。
主なリリース内容は以下のものです。
- パフォーマンス向上
- createGlobalStyleAPI
- asprop
- Comp.extendの削除
- React v16のStrictMode準拠
- React v16のrefのサポート

asめっちゃ便利

パフォーマンス向上

内部メモリの最適化やリファクタリングなどにより、16.1kBから15kB未満になり、コンポーネントのマウントは最大25%、再レンダリングは7.5%のスピードアップを実現しています。

createGlobalStyleAPI

以前のinjectGlobalは、動的なアップデートができない、ホットリロードに対応していない、コンポーネントとして利用できないと言った問題がありました。
新しいcreateGlobalStyleは、Reactのコンポーネントツリーに組み込むことができ、これにより動的なアップデート、ホットリロードが可能になり、他のstyled componentと同じようにツリーの中に組み込むことができます。

import { createGlobalStyle, ThemeProvider } from "styled-components";
// Global styles but theme- and update-able!
const GlobalStyle = createGlobalStyle`
  html {
    background: ${p => p.backgroundColor};
    color: red;
    font-family: ${p => p.theme.fontFamily};
  }
`;
export default function App() {
  return (
    <ThemeProvider theme={{ fontFamily: "Helvetica Neue" }}>
      <GlobalStyle backgroundColor="turquoise" />
    </ThemeProvider>
  );
}

Comp.extendの削除

ラップされたstyled componentは自動的に折りたたまれて、1つのコンポーネントだけがレンダリングされるようになりました。
以前はComp.extendAPIによって、拡張しているコンポーネントがstyled componentであることに基づいて最適化が行われていたのですが、styled(StyledComp)が自動的に同じような最適化を行ってくれるようになったため、Comp.extendは不要になり削除されました。

asprop

実行時に動的にレンダリングされるものを変更するためのaspropがネイティブサポートされました。
どういうことかと言うと、aspropで指定することによって他のHTMLタグでもスタイルが適用できます。

import styled from "styled-components"
import { Link } from "react-router-dom"
// <Component /> renders a div to the DOM
const Component = styled.div`
  color: red;
`
<Component>Hello World!</Component>
// But we can also make it render any other HTML tag or component!
<Component as="span">Hello World!</Component>
<Component as={Link} to="home">Hello World!</Component>

React v16のStrictMode準拠

React v16のStrictModeに対応しました。
StrictModeはアプリの潜在的な問題を検出するために追加されたコンポーネントです。
https://reactjs.org/docs/strict-mode.html
しかし、これによってv15以下のサポートは外さなければならなくなりました。

React v16のrefのサポート

React v16で、React.forwardRefAPIにより、innerRefが廃止されるため、それに対応しました。
https://reactjs.org/docs/forwarding-refs.html

import styled from "styled-components"
const Component = styled.div`
  color: red;
`
// Later in your render function
<Component ref={element => { this.myRef = element; }}
43
23
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
43
23