概要
これを
<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の配列をもとに連想配列を作成
- 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>
);
}
}
最後に
プラットフォーム別に調整しづらい