使用Styled-Components,如何在Styled Component外部设置颜色数组?

AnA*_*ice 6 javascript css reactjs styled-components

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

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

  blues: {
    20: '#asd',
    5: '#fasd',
  }
  ...
Run Code Online (Sandbox Code Playgroud)

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

import React from 'react';
const colors = ['#GSA', '#AEA', '#asd', '#fasd', '#AEA'];
Run Code Online (Sandbox Code Playgroud)

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

const getBackgroundColor = ({ currentPosition }) => {
  const color = colors[(currentPosition) % colors.length];
  return color;
};
Run Code Online (Sandbox Code Playgroud)

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

const StyledCard = styled.div`
  background: ${getBackgroundColor};
  ...
`;
Run Code Online (Sandbox Code Playgroud)

问题是我的颜色数组是在没有样式组件主题的情况下设置的.

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

Tal*_*aul 2

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

颜色.js

export const fadedPurple = '#9f91ad';
export const success = '#4fa579';
export const failure = '#ca374d';
Run Code Online (Sandbox Code Playgroud)

按钮组件

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>
  )
Run Code Online (Sandbox Code Playgroud)