【问题标题】:How to set props fro dynamic value in styles in react native如何在本机反应中为样式中的动态值设置道具
【发布时间】:2019-12-30 09:08:21
【问题描述】:

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

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>

【问题讨论】:

标签: css reactjs react-native


【解决方案1】:

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

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

不要忘记从CardMainView 中删除backgroundColor: this.props.colorCode

【讨论】:

    猜你喜欢
    • 2022-01-18
    • 2021-05-27
    • 1970-01-01
    • 2017-11-26
    • 1970-01-01
    • 2019-08-04
    • 1970-01-01
    • 2020-01-25
    • 1970-01-01
    相关资源
    最近更新 更多