I want to style list items in my React Native app based on a style name saved for each item in my database. The style name in the database references a "class" in my styles but I'm not sure how to call the "class" correctly in my view
so it renders the style.
Database entry (here redItem
is a class name):
var ITEMS_DATA = [
{location: 'Manhattan', color: 'redItem'} ];
View:
<TouchableHighlight key={i} style={[styles.listItem, styles.{{item.color}}]}>
<View>
<Text style={CardStyles.gameSection}>{item.location}</Text>
</View> </TouchableHighlight>
Style from StyleSheet:
redItem: { backgroundColor: '#e91e63' },
Note the styles.{{game.color}}
in TouchableHighlight
- this is where I want to pull in styles via the referenced class name.
Currently when I load this is the simulator I get a SyntaxError
.
Please note that I'm a very junior programmer. Thanks!
To access a dynamically named property from a Javascript object, you use object[name]
. In your case, you would access it with styles[item.color]
. This would look as follows in your code snippet:
<TouchableHighlight key={i} style={[styles.listItem, styles[item.color]]}>
<View>
<Text style={CardStyles.gameSection}>{item.location}</Text>
</View> </TouchableHighlight>
I tested this locally, and accessing properties of a StyleSheet
like this is working.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.