[英]With a Styled-Components, how to set an array of colors outside of the Styled Component?
theme.js - I have a Styled-Components theme which contains all of my app's color variations. theme.js - 我有一个Styled-Components主题,其中包含我所有应用程序的颜色变化。
const colors = {
purples: {
60: '#AEA',
50: '#GSA',
},
blues: {
20: '#asd',
5: '#fasd',
}
...
I then have a UI component where I need to define an array of colors in a specific order: 然后我有一个UI组件,我需要按特定顺序定义颜色数组:
import React from 'react';
const colors = ['#GSA', '#AEA', '#asd', '#fasd', '#AEA'];
I later use this colors
array to find the right color to use in my component based on state: 我后来使用这个colors
数组来找到基于状态在我的组件中使用的正确颜色:
const getBackgroundColor = ({ currentPosition }) => {
const color = colors[(currentPosition) % colors.length];
return color;
};
This function is used within my styled-component like so: 这个函数在我的样式组件中使用,如下所示:
const StyledCard = styled.div`
background: ${getBackgroundColor};
...
`;
The problem is my colors array is being set without the styled-components theme. 问题是我的颜色数组是在没有样式组件主题的情况下设置的。
How can I define a const colors
using my theme when it is outside the styled element? 当它在样式元素之外时,如何使用我的主题定义const colors
?
So I have done this in react-native and should be pretty similiar. 所以我用react-native做了这个,应该非常相似。 I have a file called colors.js with all of the colors then I import them as an object so that was I can say colors[TheNameOfTheColorIWant]
我有一个名为colors.js的文件,其中包含所有颜色,然后我将它们作为对象导入,这样我就可以说colors[TheNameOfTheColorIWant]
colors.js colors.js
export const fadedPurple = '#9f91ad';
export const success = '#4fa579';
export const failure = '#ca374d';
Button Component 按钮组件
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>
)
Create a js file with this pattern: 使用此模式创建js文件:
'use strict';
var React = require('react-native');
var myStyle = React.StyleSheet.create({
red: {backgroundColor: 'red' },
blue: {backgroundColor: 'blue' }
)}
module.exports = myStyle;
your component js use require to use that style sheet 你的组件js使用require要使用该样式表
var customStyle = require('../the/path/to/commonStyleSheet');
Use now like this: 现在使用这样:
<View style = {customStyle .red} />
<View style = {customStyle .blue} />
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.