【发布时间】: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<ViewStyle>'
我还尝试了以下方法:
<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