在React Native样式表中,如何将多个样式组合在一起

时间:2018-06-08 07:50:40

标签: react-native

如果可能的话,我想在React Native中将共享样式组合在一起,就像它在CSS样式表中的可能方式一样。

module.exports = {
    "one": {
        justifyContent: 'flex-start',
        padding: 5,
        backgroundColor: 'green'
    },
    "two": {
        justifyContent: 'flex-end',
        padding: 5,
        backgroundColor: 'green'
    }
}

目前,我的React Native样式表看起来像..

module.exports = {
    "oneAndTwo": {
        padding: 5,
        backgroundColor: 'green'
    },
    "one": {
        justifyContent: 'flex-start'
    },
    "two": {
        justifyContent: 'flex-end'
    }
}

<View style={[styles.oneAndTwo, styles.one]}>
    <Text style={styles.oneAndTwoText}>One</Text>
</View>
<View style={[styles.oneAndTwo, styles.two]}>
    <Text style={styles.oneAndTwoText}>Two</Text>
</View>

我当然可以为元素添加多个样式..

template

..但我正在寻找CSS方式是否可行。

编辑 - 感谢目前为止的样式管理建议。我会在周末试用它们,因为我会更多地了解React Native并在我有机会理解并应用它们后回复。

看起来没有任何简单的方法可以设置多种风格的课程&#39;就像在CSS中一样,我会尝试其他想法。

3 个答案:

答案 0 :(得分:1)

我发现这是最简单的方式就是这样。首先,我有一个保存变量的文件

/* styles/variables.js */
const styleVariables = {

  // Fonts
  baseFontSize: 16,
  largeFontSize: 24,

  // Icons
  smallIconSize: 24,
  mediumIconSize: 36,

  // Colors
  mainColor: '#e85e45',
  secondaryColor: '#a0c5d8',
  offWhite: '#f4f4f4',
  darkColor: '#404040',

  // Dimensions
  headerHeight: 70,
  shadowSize: 6
};
export default styleVariables;

我在其他样式文件中引用我的变量,其中相关信息被分组:

/* styles/presentation.js */
import variables from './variables';

export const shadow = {
  shadowColor: variables.darkColor,
  shadowRadius: variables.shadowSize,
  shadowOpacity: 0.35,
  shadowOffset: {width: 0, height: 0}
};

export const centered = {
  alignItems: 'center'
  justifyContent: 'center'
}

export const button = {
    width: variables.buttonSize,
    height: variables.buttonSize,
    borderRadius: variables.buttonSize / 2,
}

然后在我的组件中我可以组合这些样式:

import variables from './../styles/variables';
import {centered, shadow, button} from './../styles/presentation';

class RoundButton extends React.PureComponent {

  render() {
    return (
        <View style={styles.button}>
          {this.props.children}          
        </View>
    );
  }
}

const styles = StyleSheet.create({
  button: {
    ...button,
    ...centered,
    ...shadow
  }

答案 1 :(得分:0)

您可以尝试这样

test:
  service: Disk
  root: <%= Rails.root.join("tmp/test_storage") %>

答案 2 :(得分:0)

在JavaScript中,您应该使用Object.assign()来合并对象。 例如:

        let justifyContent = {justifyContent: 'flex-start'};
        let alignItems = {alignItems: 'center'};
        let flex = {flex: 1};
        let backGroundColor = {backgroundColor: 'white'}

        let myStyle = Object.assign(justifyContent, alignItems, flex, backGroundColor)
        console.log(log_sign_data, myStyle)

结果:

 myStyle = {justifyContent: "flex-start", alignItems: "center", flex: 1, backgroundColor: "white"}