先日、styled-components v4がリリースされました。
主なリリース内容は以下のものです。
- パフォーマンス向上
-
createGlobalStyle
API -
as
prop -
Comp.extend
の削除 - React v16のStrictMode準拠
- React v16の
ref
のサポート
as
めっちゃ便利
パフォーマンス向上
内部メモリの最適化やリファクタリングなどにより、16.1kBから15kB未満になり、コンポーネントのマウントは最大25%、再レンダリングは7.5%のスピードアップを実現しています。
createGlobalStyle
API
以前の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.extend
APIによって、拡張しているコンポーネントがstyled componentであることに基づいて最適化が行われていたのですが、styled(StyledComp)
が自動的に同じような最適化を行ってくれるようになったため、Comp.extend
は不要になり削除されました。
as
prop
実行時に動的にレンダリングされるものを変更するためのas
propがネイティブサポートされました。
どういうことかと言うと、as
propで指定することによって他の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.forwardRef
APIにより、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; }}