【问题标题】:Different background colors in flatlist平面列表中的不同背景颜色
【发布时间】:2020-01-23 21:38:03
【问题描述】:

我有一个带有对象的FlatList,每个对象都有特定的颜色。我想将该颜色传递给FlatList 的项目样式。

播放列表类:

class Playlist {
  id: number;
  name: String;
  color: String;
  songs: Song[];
  constructor(id: number, name: String, color: String) {
    this.id = id;
    this.name = name;
    this.color = color;
    this.songs = [];
  }
}

播放列表组件:

class Playlists extends Component<Props, State> {
  constructor(props) {
    super(props);
    this.state = {
      playlists: [
        new Playlist(0, 'Favorite Songs', 'purple'),
        new Playlist(1, 'Rock', 'green'),
        new Playlist(2, 'Pop', 'blue'),
        new Playlist(3, 'Electronic', 'yellow'),
      ],
    };
  }

  render() {

    return (
      <FlatList
        data={this.state.playlists}
        renderItem={({item: playlist}) => (
          <View>
            <View style={styles.namePart}>
              <View
                style={{
                  backgroundColor: playlist.color,   //Here I want to pass the color of the Playlist object to the backgroundColor property, but it does not work
                }}
              />
              <Text style={styles.name}>{playlist.name}</Text>
            </View>
            <Text style={styles.count}>{playlist.songs.length}</Text>
          </View>
        )}
      />
    );
  }
}

我收到错误消息:No overload matches this call. Type '{ backgroundColor: String; }' is not assignable to type 'StyleProp&lt;ViewStyle&gt;'

我还尝试了以下方法:

<View
    style={StyleSheet.create({
        backgroundColor: playlist.color,
    })}
/>

但这里显示以下错误:Type 'String' is not assignable to type 'ViewStyle | TextStyle | ImageStyle'. 但是当我在const style = StyleSheet.create({}) 中创建一个样式并传递例如backgroundColor: 'blue' 时,这有效。在这种情况下,'blue' 不是字符串吗?我真的不明白。

如何更改我的代码才能正常工作?

【问题讨论】:

    标签: react-native


    【解决方案1】:

    您在 Typescript 中混淆了 StringstringStringJavascript string objectstring 是 Typescript 字符串值以及您的样式类型所期望的。

    只需将您的 Playlist 类更改为:

    class Playlist {
      id: number;
      name: string;
      color: string;
      songs: Song[];
      constructor(id: number, name: string, color: string) {
        this.id = id;
        this.name = name;
        this.color = color;
        this.songs = [];
      }
    }
    

    【讨论】:

    • 非常感谢!这带来了清晰度。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多