如何在React Native中以样式为动态值设置道具

时间:2019-08-26 07:22:14

标签: css reactjs react-native

我从服务器中获取数据,我必须在其中设置样式表中的道具以动态更改背景颜色。但我遇到错误

undefined is not an object (evaluating 'this.props.colorCode')

这是我的代码

class TopCategoryCard extends Component {
  render() {
    return (
      <View style={styles.container}>

        <View style={styles.CardMainView}>
        <View style={styles.ThirdLayerStyle}>
        </View>
        <View style={styles.SecondLayerStyle}>
         </View>
         <View style={styles.FirstLayerStyle}>
         <Image resizeMode={'contain'} style={styles.CatImageStyle}
          source={this.props.imageUri}
        />
         </View>
        <Text numberOfLines={1} style={{color:'#fff' ,  fontSize:13, top:28  , marginLeft:25  , marginRight:20, fontFamily: "poppinsregular"}}>{this.props.name}</Text>
       </View>

      </View>
    );
  }
}
const styles = StyleSheet.create({
  container: {
    padding:5
  },
  CardMainView:{
    flexDirection:'row',
    borderRadius:4,
    backgroundColor: this.props.colorCode,
    height:80,
    elevation:3,
    shadowColor:'#000',
    overflow:'hidden',
  }
  }

在上述代码中,我成功获取了图像和名称,但在更改颜色代码时遇到错误,请帮忙

变色代码

<ScrollView
                      style={{ marginTop:15 , marginLeft:-5  }}
                      horizontal={true}
                      showsHorizontalScrollIndicator={false}>
                      <FlatList 
                        data={this.state.data}
                        keyExtractor={(x, i) => i.toString()}
                        renderItem={({ item }) => (
                          <TouchableOpacity 
                            activeOpacity={0.9}
                            onPress={() =>
                              this.props.navigation.navigate(
                                "JobbyCategorylist",
                                { slug: item.slug }
                              )
                            }
                          >
                            <TopCategoryCard
                              imageUri={{ uri: `${item.url}` }}
                              name={`${entities.decode(item.name)}`}
                              colorCode={item.color}
                            />
                          </TouchableOpacity>
                        )}
                        horizontal={true}
                      />
                    </ScrollView>

1 个答案:

答案 0 :(得分:3)

您不能为StyleSheet属性动态分配值。相反,您可以尝试如下操作:

<View style={[ styles.CardMainView, {backgroundColor: this.props.colorCode} ]}>

别忘了从backgroundColor: this.props.colorCode中删除CardMainView