【问题标题】:Insert Dynamic Variable Into React Native Stylesheet将动态变量插入 React Native 样式表
【发布时间】:2019-02-18 00:48:31
【问题描述】:

我有一个想要动态设置样式的反应原生视图。 reaction 的值将来自 API,所以我想将它传递到我的样式表中

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

样式表如下所示

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'
  },
    }

其中ClearRainThunderStorm 可以是reaction 的值 我想动态提供reaction 值。

我已经尝试过这样做

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

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

但它们似乎都不起作用。 任何解决此问题的帮助将不胜感激。

【问题讨论】:

    标签: javascript css reactjs react-native


    【解决方案1】:

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

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

    然后在你的&lt;View/&gt; 标签中提供反应

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

    【讨论】:

    • 要动态获取对象条目,您可以尝试 object[String(outerKey)].innerKey 或者您可以尝试 Object 类。例如Object.entries(object),它将返回一对数据key:value,并通过键访问值。 const color = Object.values(weatherConditions[reaction]).color
    猜你喜欢
    • 2019-01-20
    • 2016-10-10
    • 1970-01-01
    • 2019-07-17
    • 2018-10-20
    • 2016-12-11
    • 1970-01-01
    • 2020-10-01
    • 2021-07-27
    相关资源
    最近更新 更多