React Native External Stylesheet

前端 未结 9 886
你的背包
你的背包 2021-02-03 23:12

Is there a way in React Native that I can put all of my styles in a single file so it can easily be maintained (from my perspective) like in HTML we have a .css fil

相关标签:
9条回答
  • 2021-02-03 23:45

    The whole process of defining styles in my JavaScript caused me a lot of confusion when I first moved over to React Native from Ionic so I hope this helps...

    Firstly, you've got to understand that React Native is NOT just an application running in a native WebView. Rather than rendering divs and spans your JavaScript is actually producing higher-level, platform-specific components.

    Therefore we can't apply the same styling rules (via external .css stylesheets) like you would a hybrid application written using another framework like Ionic. Well not entirely anyway (see below).

    Both options mentioned above are valid solutions. Using:

    • Separate JavaScript files to make your styles more modular; and
    • Using libraries to transpile CSS to React Native StyleSheet objects.

    Note on latter option: Libraries like postcss-js won't enable you to use your CSS the way you normally would i.e. styling based on CSS selectors like .class and #id. Styles will still need to be passed through to components via props.

    0 讨论(0)
  • 2021-02-03 23:46

    You can try my project rn-less.

    It isolates your stylesheet from your jsx/js files with less.js.

    And I have a VS Code extension for it, with which you can jump between .less files and .js/.jsx files easily.

    0 讨论(0)
  • 2021-02-03 23:48

    I agree to @Chris Geirman solution. you can just create stylesSheet as mention above by Chris and import to any view. In case if you want to merge external styleSheet to your individual view/component stylesheet then you can use ES6 new feature Object.assign like so:

    styles = require('./StyleSheet');

    const viewStyle = Object.assign(styles, StyleSheet.create({ ... }); );

    0 讨论(0)
提交回复
热议问题