简体   繁体   中英

Using React Native StyleSheet like class of HTML

I had this question a long time ago. What if I use React Native StyleSheet like class of HTML? I really did use it. I have a lot of styles (names are based on Bootstrap Class Name).

import { StyleSheet } from "react-native";

const s = StyleSheet.create({
  flex: { flex: 1 },
  flexCenter: {
    flex: 1,
    alignItems: "center",
    justifyContent: "center",
    paddingVertical: 24,
  },
  p0: { padding: 0 },
  p1: { padding: 4 },
  p2: { padding: 8 },
  textLight: { color: "#eee" },
  fsLg: { fontSize: 18 },
  ... and so on
});

export default s;

Then, in components I use it like this.

<Text style={[s.fsLg, s.p2, s.textLight]}>Title</Text>

I do not use it anymore because I had a feeling it was a bad practice. I don't know surely. I have read official react native styling. They did not mention this is bad. How do anyone think?

When in doubt, check the docs: https://reactnative.dev/docs/style

The style prop can be a plain old JavaScript object. That's what we usually use for example code. You can also pass an array of styles - the last style in the array has precedence, so you can use this to inherit styles.

From the second paragraph. This is a recommended practice.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM