LoginSignup
4
5

More than 3 years have passed since last update.

ReactNativeのStyleSheetの中で変数を使う。

Last updated at Posted at 2019-03-31

alt

StyleSheetで変数を使うには

style自体をアロー関数にすればいい。
少し記述量は増えるし、本当に少しだけアプリが遅くなるが、今の所これで満足している。

const  SMALL = 10
...

<Text style={S.text(SMALL)}>Text</Text>

...

const S = StyleSheet.create({
  text: (SMALL) => ({
    fontSize: SMALL,
    color: 'white'
  }),
  container: {
    flex: 1
  }
}

追記

なお、sytleとして、StyleSheet.createを使う代わりに、plain objctを渡す人もいるが、以下の二点の理由によりやめた方がいい。

1 可読性の低下

単純に、StyleSheetを使わないと、styleが、コードの中に分散しがち。

2 パフォーマンスの低下

StyleSheetは、styleをIDにマッピングする。このことにより、毎回のオブジェクトの生成が必要なくなるため、パフォーマンスが上がる。

4
5
0

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
4
5