ReactNativeでglamorous-nativeとstyled-componentsを使ってみた

ReactNativeでスタイルを書きやすくしてくれるライブラリがある

styled-comopnentsはスター数が1万を超えの人気ライブラリ

主にウェブの方で使われてるがReactNativeにも対応してるっぽい

glamorous-nativeは後発でstyled-componentsなどに影響を受けて出てきたライブラリ

同じようなことが出来る

なぜ使うのか?

  • スタイルに名前を付けなくて良くなる
  • コンポーネントにどのスタイルがかかっているか一目瞭然
  • 簡単にスタイルを設定出来るようになる

などでしょうか

ちょっとスタイルが違うだけのコンポーネントが乱立して雑にならないように気をつける

どちらが良いのか?

まず普通にスタイルを適用する書き方だとこうなる(一部省略)

import { Text, StyleSheet } from 'react-native'

const styles = StyleSheet.create({
  text: {
    fontSize: 20,
    color: 'red'
  }
})

<Text style={styles.text}>Hello!</Text>

styled-components

次にstyled-componentsだとこうなる

import styled from 'styled-components/native'

const MyText = styled.Text`
  fontSize: 20,
  color: red
`

<MyText >Hello!</MyText>

ウェブの時みたいに props は渡せないみたい

glamorous-native

glamorous-nativeだとインラインでpropsにスタイル名を渡す形式で書ける

import glamorous, { Text } from 'glamorous-native'

<Text color="red" fontSize={20}>

または、前もって定義して使うことも可能

import glamorous from 'glamorous-native'

const MyText = glamorous.text({
  fontSize: 20,
  color: 'red'
})

<MyText >Hello!</MyText>

styled-componentsだとスタイルのキャッシュが効いてない?

こんな記事があった

Why you don’t need Styled-Components in a React Native app.

普通に書いた時の styles はプレーンなオブジェクトでも動くが

StyleSheet.create はスタイルをキャッシュして再利用してるので必要らしい

だがstyled-componentsはキャッシュしてくれてないらしくglamorous-nativeはそこらへんをよしなにやってくれている

const styles = StyleSheet.create({
  text: {
    fontSize: 20,
    color: 'red'
  }
})

// ↓↓ これでも動くがキャッシュされない

const styles = {
  text: {
    fontSize: 20,
    color: 'red'
  }
}

glamorous-nativeは他にも色々機能がある

既存のコンポーネントのスタイルを拡張して使う

const MyTextComp = glamorous(MyText)({ fontStyle: 'italic' })

<MyTextComp>Hello!</MyTextComp>

propsを自分で操る

const MyText = glamorous.text(
  {
    fontSize: 20,
    color: 'red'
  },
  (props) => ({
    fontWeight: props.noBold ? 'normal' : 'bold'
  })
)

<MyText>Hello bold!</MyText>
<MyText noBold>Hello noBold!</MyText>

このあたりはREADMEに詳しく例が乗ってるので助かる

GitHub - robinpowered/glamorous-native: React Native component styling solved💄

その他、アニメーションと合わせて使う時のサンプルと

ナイトモードなどのテーマを実装したい時のサンプルがリポジトリにあるので参考になる

https://github.com/robinpowered/glamorous-native/tree/master/examples

結論

glamorous-nativeが良さそう

github.com

適当に書いたコード↓

https://github.com/rskull/glamorous-native-example/blob/master/App.js

参考リンク

Why you don’t need Styled-Components in a React Native app.

https://github.com/styled-components/styled-components

https://github.com/robinpowered/glamorous-native