React Native全局样式

Pat*_*atm 83 react-native

我是React的新手,我了解基于组件的内联样式的好处.但我想知道是否有一种体面的方式来拥有某种全球风格.例如,我想在我的应用程序中使用相同的文本和按钮着色.

而不是在每个组件中重复(并且随后必须在x位置更改它),我最初的想法是在它自己的文件中创建一个"基础"StyleSheet类并将其导入我的组件中.

是否有更好或更"反应"的方式?

bor*_*mes 112

您可以创建可重用的样式表.例:

style.js

'use strict';

var React = require('react-native');

var {
  StyleSheet,
} = React;

module.exports = StyleSheet.create({

alwaysred: {
    backgroundColor: 'red',
    height: 100,
    width: 100,
},

});
Run Code Online (Sandbox Code Playgroud)

在您的组件中:

var s = require('./style');
Run Code Online (Sandbox Code Playgroud)

...然后:

<View style={s.alwaysred} ></View>
Run Code Online (Sandbox Code Playgroud)

  • 现在你可以使用'react-native'中的`import {StyleSheet};` (17认同)

Bar*_*ker 76

为您的样式创建一个文件(IE,Style.js).

这是一个例子:

import { StyleSheet } from 'react-native';

export default StyleSheet.create({
  container: {
    flex: 1
  },
  welcome: {
    fontSize: 20
  }
});
Run Code Online (Sandbox Code Playgroud)

在要使用样式的任何文件中,添加以下内容:

import styles from './Style'
Run Code Online (Sandbox Code Playgroud)

  • 我怀疑这个答案现在更相关! (7认同)
  • './Styles' 应为 './Style' 以匹配文件名 Style.js (3认同)

Rob*_*Rob 9

如果你只是想设置一些全局变量,你可以试试.

AppStyles.js

export default AppStyles = {
    colour: {
        background: '#f4f9fd',
        font: '#434e5a',
        primary: '#ff3b30'
    }
}
Run Code Online (Sandbox Code Playgroud)

index.ios.js

import AppStyles from './AppStyles';

const styles = StyleSheet.create({
    container: {
        backgroundColor: AppStyles.colour.background
    }
});
Run Code Online (Sandbox Code Playgroud)


vit*_*ets 8

您也可以尝试使用支持全局样式变量的react-native-extended-stylesheet:

// app.js
EStyleSheet.build({
   buttonColor: 'green'
});

// component.js
var styles = EStyleSheet.create({
  button: {
    backgroundColor: '$buttonColor',
    ...
  }
});
Run Code Online (Sandbox Code Playgroud)


Ami*_*bar 8

您必须创建一个文件来存储其中的所有样式,如' styles.js ',并根据需要编写css类型代码

'use strict';
import {StyleSheet} from 'react-native';

export default StyleSheet.create({

    container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#F5FCFF',
    },

    title: {
        fontSize: 10,
        color: '#000',
        backgroundColor: '#fff'
    },

    button: {
        fontSize: 12,
        color: '#000',
        backgroundColor: '#fff'
    }

});
Run Code Online (Sandbox Code Playgroud)

现在您可以使用全局样式

import React, { Component } from 'react';
import { View, Button } from 'react-native';
import StyleSheet from './config/styles';

export default class App extends Component {

  render() {
    return (
      <View
        style={StyleSheet.container}>
        <Button
          style={StyleSheet.button}
          title="Go to Lucy's profile"
        />
      </View>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)