1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

ReactNativeのインラインスタイルを整理する

Last updated at Posted at 2019-04-04

概要

これを

<Text style={{fontSize: 20, textAlign: 'center', margin: 10}}>Welcome to React Native!</Text>

こんな感じに書きたい。

<Text style={[fs20, tac, m10]}>Welcome to React Native!</Text>

イメージはBootstrapにあるm-0 w-25など、
ようは汎用CSS、汎用クラスと呼ばれているやつをやりたい。

環境

ReactNative 0.59.3

方法

tac textAlign: 'center'

const _base = StyleSheet.create({
  tac: {
    textAlign: 'center',
  },
});

fs20 fontSize: 20
m10 margin: 10

const attrs = {
  fontSize: 'fs',
  margin: 'm',
};

const props = [
  10,
  20,
];

const styleGenerator = (attributes, properties) => {
  let hash = {};
  for (attr in attributes) {
    for (i = 0; i < properties.length; i++) {
      let h = {};
      h[attr] = properties[i];
      hash[`${attributes[attr]}${properties[i]}`] = h;
    }
  }
  return hash;
};

const whmp = StyleSheet.create(styleGenerator(attrs, props));
  1. プロパティと値の配列を用意
  2. 1の配列をもとに連想配列を作成
  3. StyleSheet.create

Base.js

最終的にはこんな感じになります。

import { StyleSheet } from 'react-native';

const _base = StyleSheet.create({
  tac: {
    textAlign: 'center',
  },
});

const attrs = {
  fontSize: 'fs',
  margin: 'm',
};

const props = [
  10,
  20,
];

const styleGenerator = (attributes, properties) => {
  let hash = {};
  for (attr in attributes) {
    for (i = 0; i < properties.length; i++) {
      let h = {};
      h[attr] = properties[i];
      hash[`${attributes[attr]}${properties[i]}`] = h;
    }
  }
  return hash;
};

const whmp = StyleSheet.create(styleGenerator(attrs, props));

const base = { ..._base, ...whmp };

export default base;

他のプロパティ、値の追加も配列に追記するだけです。

使い方


import React, {Component} from 'react';
import {Platform, Text} from 'react-native';
import s from './Base';

type Props = {};
export default class App extends Component<Props> {
  render() {
    return (
      <Text style={[s.fs20, s.tac, s.m10]}>Welcome to React Native!</Text>
    );
  }
}

最後に

プラットフォーム別に調整しづらい

参考

@YutamaKotaro様 【React-Native】StyleSheetについて

1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?