【问题标题】:StyleSheet - Extend Style Value in React NativeStyleSheet - 在 React Native 中扩展样式值
【发布时间】:2018-04-23 02:06:42
【问题描述】:

有办法做这样的事情吗?

const styles = StyleSheet.create({
  content: {
    alignItems: 'center',
    flex: 1,
    justifyContent: 'center'
  },
  mainColor: { color: '#FFFFFF' },
  usernameIcon: {
    {this.styles.mainColor} // <-- How import the style, instead does write the code - color: '#FFFFFF'?
  },
  usernameItem: {
    backgroundColor: '#FF8484',
    borderColor: '#FFFFFF',
    paddingTop: 7
  },
});

在我的组件中添加许多类,这非常冗长,我可能会做类似上面代码的事情。

【问题讨论】:

    标签: css react-native stylesheet


    【解决方案1】:

    React Native 中没有样式继承语法(如 CSS 预处理器)。

    但既然都是 JS 你可以用 JS 来做:

    const MAIN_COLOR = 'white';
    
    const someStyle = {
      padding: 5,
      margin: 5,
    }
    
    const styles = StyleSheet.create({
      usernameIcon: {
        color: MAIN_COLOR,
        ...someStyle,
      },
      generalStyle: {
        backgroundColor: 'white',
      }
    })
    
    // you can also combine styles in the component
    // note that the latter style will override duplicated styles
    <View style={[styles.usernameIcon, styles.generalStyle]} />
    

    【讨论】:

    • 我使用了一段时间的技巧,但我确实遇到了障碍。似乎如果您尝试覆盖 someStyle 内的任何值 generalStyle 这将不起作用。我花了很多时间才发现这是罪魁祸首,而且我还没有找到解决这个问题的方法。
    • 感谢您的快速响应,但我只是尝试过没有成功。如果一个 prop 在一个简单对象中声明,它似乎无法覆盖它。
    • 是的,它也完全适合我。看来我的问题可能与 react-native-elements 的 Button 组件有关。我在一个使用这个库的旧版本的项目中找到了它,所以它可能在此期间已经修复了。非常感谢。
    猜你喜欢
    • 2020-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-02
    • 1970-01-01
    • 2020-10-13
    • 2021-09-21
    相关资源
    最近更新 更多