【问题标题】:With a Styled-Components, how to set an array of colors outside of the Styled Component?使用 Styled-Components,如何在 Styled 组件之外设置一组颜色?
【发布时间】:2018-12-02 18:50:27
【问题描述】:

theme.js - 我有一个 Styled-Components 主题,其中包含我应用的所有颜色变化。

const colors = {
  purples: {
    60: '#AEA',
    50: '#GSA',
  },

  blues: {
    20: '#asd',
    5: '#fasd',
  }
  ...

然后我有一个 UI 组件,我需要在其中按特定顺序定义一组颜色:

import React from 'react';
const colors = ['#GSA', '#AEA', '#asd', '#fasd', '#AEA'];

我稍后使用这个 colors 数组根据状态找到要在我的组件中使用的正确颜色:

const getBackgroundColor = ({ currentPosition }) => {
  const color = colors[(currentPosition) % colors.length];
  return color;
};

这个函数在我的样式组件中使用,如下所示:

const StyledCard = styled.div`
  background: ${getBackgroundColor};
  ...
`;

问题是我的颜色数组没有设置样式组件主题。

const colors 在样式元素之外时,如何使用我的主题定义它?

【问题讨论】:

    标签: javascript css reactjs styled-components


    【解决方案1】:

    用这个模式创建一个js文件:

    'use strict';
    
    var React = require('react-native');
    
    var myStyle = React.StyleSheet.create({
       red: {backgroundColor: 'red' },
       blue: {backgroundColor: 'blue' }
    )}
    module.exports = myStyle;
    

    您的组件 js 使用需要使用该样式表

    var customStyle = require('../the/path/to/commonStyleSheet');
    

    现在这样使用:

    <View style = {customStyle .red} />
    <View style = {customStyle .blue} />
    

    【讨论】:

      【解决方案2】:

      所以我在 react-native 中做到了这一点,应该非常相似。我有一个名为 colors.js 的文件,其中包含所有颜色,然后我将它们作为对象导入,这样我就可以说 colors[TheNameOfTheColorIWant]

      colors.js

      export const fadedPurple = '#9f91ad';
      export const success = '#4fa579';
      export const failure = '#ca374d';
      

      按钮组件

      import * as colors from '../../../assets/styles/colors';
      
      const Button = (props) => {
        const {
          onPress,
          children,
          color
        } = props;
      
        style = {
          backgroundColor: colors[backgroundColor]
        }
      
        return (
          <TouchableOpacity style={ style }
                            onPress={ onPress }
                            disabled={ disabled }>
              { children }
          </TouchableOpacity>
        )
      

      【讨论】:

        猜你喜欢
        • 2019-01-17
        • 2021-09-19
        • 2021-11-04
        • 2018-11-12
        • 2020-05-01
        • 2022-01-26
        • 1970-01-01
        • 2020-11-03
        • 2019-04-19
        相关资源
        最近更新 更多