【问题标题】:React Native - Getting Style from a Function (Android)React Native - 从函数中获取样式 (Android)
【发布时间】:2016-07-20 08:43:43
【问题描述】:

我想要实现的是,根据来自 JSON 的内容动态添加视图。例如,一个事件可以用红色表示,另一个可以用蓝色表示。应用程序应根据此插入视图。

class MainPage2 extends Component {


 constructor () {  
super()
var sleepTime = ["15/07/2016 15:00:00", "15/07/2016 14:20:30"];
var minuteDifference = Math.round((((sleepTime[0] - sleepTime[1]) / 1000)/60));

var width = {timeAsleep: 120, timeAwake:60, timeAway:60}
this.state = {
  timeAsleep: width.timeAsleep, 
  timeAwake: width.timeAwake,
  timeAway:  width.timeAway, 
  array: [1,2]
}  //set the changeable values, we will get it from Json in our app
  } styler (num) {


    if (num == 1)
    return styles.AsleepStyle;

    if (num==2)
    return styles.AwakeStyle;

    if (num==3)
    return styles.AwayStyle;

    return styles.AwayStyle;
  }

  render () {
   const {timeAsleep, timeAwake, timeAway} = this.state
  let Arr = this.state.array.map((a, i) => {
 return <View key={i} style={this.styler(a)}></View> });

   return (
   <ScrollView>

    <Text>First</Text>
    <View style={this.styler}/>
    { Arr }

    <Text>Second</Text>
    <TouchableHighlight onPress={ () => this._onPressOut() }>
      <Text>Push</Text>
    </TouchableHighlight>

  <View style={styles.viewLayout}>


    <View style={[styles.bar, styles.AsleepStyle, {width: timeAsleep}]}/> 
    <View style={[styles.bar, styles.AwakeStyle, {width: timeAwake}]}/>
    <View style={[styles.bar, styles.AwayStyle, {width: timeAway}]}/>
  </View>
   </ScrollView>  

   )  }}

const styles = StyleSheet.create({
viewLayout: {
   flex: 1, flexDirection: 'row',padding:20
},

 bar: {


height: 18

},

AsleepStyle: {
backgroundColor: '#F55443'
},
AwakeStyle: {
backgroundColor: '#FCBD24'
},
   AwayStyle: {
backgroundColor: '#59838B'
}
});

module.exports = MainPage2;

提前致谢

【问题讨论】:

  • 从您的问题中并不清楚您的代码是如何构造的。更多的上下文会有所帮助。例如,这个函数在哪里定义?
  • 我编辑了这个问题。并添加了所有代码
  • 感谢您将其标记为已解决。为此,请在下方添加答案,然后单击旁边的勾号。

标签: javascript mobile reactjs react-native react-native-android


【解决方案1】:

如果 styler 在同一个类中,则使用 this.styler

 render () {
     const {timeAsleep, timeAwake, timeAway} = this.state
     let Arr = this.state.array.map((a, i) => {
     return <View key={i} style={this.styler(a)}></View> });
 }

【讨论】:

  • 谢谢,现在可以看到这个功能了,但是还是不行。
  • 你能详细说明一下吗?什么不工作?日志中有什么?
  • 有一个警告。道具类型失败:提供给“视图”的“功能”类型的无效道具“样式”,应为“对象”。在视图中
  • 。这就是问题。它是一个函数,而不是一个样式对象
  • 感谢大家的帮助,我已经解决了,我在语法上犯了一个小错误
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-28
  • 1970-01-01
  • 1970-01-01
  • 2019-02-22
  • 2020-04-14
  • 1970-01-01
相关资源
最近更新 更多