首页 > 解决方案 > 将颜色动态添加到 LinearGradient

问题描述

我正在使用这些数据来填充一个 FlatList,每个项目都包含一个 LinearGradient

const DATA = [
  {
    id: 'bd7acbea-c1b1-46c2-aed5-3ad53abb28ba',
    title: 'First Item',
    firstColor: "#f472a7",
    secondColor: "#d84351"
  },
  {
    id: '3ac68afc-c605-48d3-a4f8-fbd91aa97f63',
    title: 'Second Item',
    firstColor: "#50be71",
    secondColor: "#50be71"
  },
  {
    id: '58694a0f-3da1-471f-bd96-145571e29d72',
    title: 'Third Item',
    firstColor: "#e2bd4f",
    secondColor: "#e49074"
  }
];

我添加了两个名为“firstColor”和“secondColor”的属性来填充 LinearGradient 颜色,但这样做时遇到了一些问题。我收到此错误:

TypeError: undefined is not an object (evaluating '_ref3.secondColor')

代码:

    const Item = ({ title }, { firstColor }, { secondColor }) => (
        <LinearGradient
        colors={[{firstColor}, {secondColor} ]}
        style={styles.item}
        >
          <Text style={styles.title}>{title}</Text>
        </LinearGradient>
      );
      
      const renderItem = ({ item }) => (
        <Item title={item.title} />
      );
...

        <SafeAreaView style={styles.container}>
        <FlatList
          data={DATA}
          renderItem={renderItem}
          keyExtractor={item => item.id}
        />
      </SafeAreaView>

标签: react-nativeexpo

解决方案


尝试这个

const Item = ({ title,  firstColor, secondColor}) => (
  <LinearGradient
    colors={[firstColor, secondColor ]}
    style={styles.item}
  >
    <Text style={styles.title}>{title}</Text>
  </LinearGradient>
);
      
const renderItem = ({ item}) => (
  <Item 
    firstColor={item.firstColor } 
    secondColor={ item.secondColor } 
    title={item.title} 
  />
);


推荐阅读