【问题标题】:Overriding a Single Style Prop from Stylesheet Using React Native使用 React Native 覆盖样式表中的单个样式道具
【发布时间】:2020-01-04 02:20:15
【问题描述】:

对于 React Native,我希望使用 StyleSheet 来定义样式,然后在许多组件中使用该样式,但我想更改或覆盖一些组件的单个道具。例如,一组 10 个视图,有 5 种不同的颜色,但所有其他道具都相同。这可能吗?语法是什么样的?

我无法想象我必须定义 5 种不同的样式或使用内嵌样式。非常感谢您的帮助。

【问题讨论】:

    标签: react-native-flexbox react-native-stylesheet


    【解决方案1】:

    您可以从单个模块中导出一些全局使用的样式,并将它们导入到您需要的任何地方。然后要组合样式,您可以使用数组语法,如 [ styleA, styleB ]。

    因此,在一个简单的示例中,您可以执行以下操作:

    // ./styles.js
    
    import { StyleSheet } from 'react-native';
    
    export default StyleSheet.create({
      containerDefault: {
        height: 100,
        width: 300,
        backgroundColor: 'black'
      },
      backgroundBlue: {
        backgroundColor: 'blue'
      },
      backgroundGreen: {
        backgroundColor: 'green'
      }
    });
    

    然后……

    // ./SomeComponent.js
    
    import React from 'react';
    import { View, Text } from 'react-native';
    import styles from './styles';
    
    const ComponentBlack = () => {
      return (
        <View style={styles.containerDefault}>
          <Text>I should be black</Text>
        </View>
      );
    };
    
    const ComponentBlue = () => {
      return (
        <View style={[styles.containerDefault, styles.backgroundBlue]}>
          <Text>I should be blue</Text>
        </View>
      );
    };
    
    const ComponentGreen = () => {
      return (
        <View style={[styles.containerDefault, styles.backgroundGreen]}>
          <Text>I should be green</Text>
        </View>
      );
    };
    
    export default () => {
      return (
        <View>
          <ComponentBlack />
          <ComponentBlue />
          <ComponentGreen />
        </View>
      );
    };
    

    【讨论】:

    • 谢谢,@James!有什么理由像您一样定义众多背景颜色覆盖,而不是直接覆盖一个属性?例如:
    • 只有真正的可重用性和潜在的可读性。如果这对您更有意义,您可以内联进行。但是,如果您想为每个组件添加更复杂的修改,例如 3 或 4 个额外的样式道具,那么将所有这些都内联并在样式模块中更清晰地处理它会变得混乱。
    猜你喜欢
    • 2020-09-21
    • 1970-01-01
    • 2021-08-24
    • 1970-01-01
    • 2016-06-03
    • 2022-01-04
    • 2020-11-02
    • 2021-09-18
    • 1970-01-01
    相关资源
    最近更新 更多