Insert Dynamic Variable Into React Native Stylesheet

时间:2019-02-18 00:48:32

标签: javascript css reactjs react-native

I have a react native view i want to style dynamically. The value of reaction will be sourced from an API, so i want to pass it into my styleheet

const Weather = ({ reaction, temperature }) => {
//const bg = `weatherconditions.${reaction}.color`
return (
    <View
      style={{ backgroundColor: weatherConditions[reaction].color }}>

The stylesheet looks like this

export const weatherConditions = {
  Rain: {
    color: '#005BEA',
    title: 'Raining',
    subtitle: 'Get a cup of coffee',
    icon: 'weather-rainy'
  },
  Clear: {
    color: '#f7b733',
    title: 'So Sunny',
    subtitle: 'It is hurting my eyes',
    icon: 'weather-sunny'
  },


Thunderstorm: {
    color: '#616161',
    title: 'A Storm is coming',
    subtitle: 'Because Gods are angry',
    icon: 'weather-lightning'
  },
  Clouds: {
    color: '#1F1C2C',
    title: 'Clouds',
    subtitle: 'Everywhere',
    icon: 'weather-cloudy'
  },

  Snow: {
    color: '#00d2ff',
    title: 'Snow',
    subtitle: 'Get out and build a snowman for me',
    icon: 'weather-snowy'
  },
    }

where either Clear, Rain, ThunderStorm can be the value of reaction I want to dynamically provide the reaction value.

i have tried to do this

const Weather = ({ reaction, temperature }) => {
const bg = `weatherconditions.${reaction}.color`;
return (
    <View
      style={{ backgroundColor: bg }}
    >

and

<View
    style={{ backgroundColor: ${bg }}>

But none of them seem to work. Any help solving this will be appreciated.

1 个答案:

答案 0 :(得分:0)

不确定这是什么意思,但希望对您有所帮助。

const styles = {
  weather = reaction => ({
    backgroundColor: reaction
  })
}

然后在您的<View/>标签中提供反应

...
<View style={StyleSheet.flatten([styles.weather(reaction)])}>
 //Your code here
</View>