Reputation: 231
I am having react native components which is, according to its prop, uses two main colors. Since I want to access that variable in the stylesheet, I declare it outside of the class, and not in the state. First I declare it to be blue and then in the constructor I change its value to green. However the text it uses remains blue. I know it has something to do with rendering, but I thought since I change the value in the class constructor which is the first in the lifecycle, it would work.
I wouldn't like to use functions in the JSX style tags, so is there a solution to this?
let mainColor = Colors.blue1;
export default class Article extends Component {
constructor(props) {
super(props);
mainColor = Colors.green;
this.state={
liked: false,
withHeroImage: false
}
}
render() {
return (
<Text style={styles.title}>Lorem ipsum</Text>
);
}
}
const styles = StyleSheet.create({
title:{
fontSize: 20,
color: mainColor,
fontFamily: FontFamily.PoppinsSemibold,
marginBottom: 20
}
})
Upvotes: 1
Views: 79
Reputation: 13906
If your React
version is 16.8
or higher, you can use the effect hook
.
a link that allows me to directly execute my answer
Usage
import React, { useState, useEffect } from 'react';
import { Text, View, StyleSheet,Button } from 'react-native';
export default function Article() {
const [maincol, setColor] = useState("blue");
const styles = StyleSheet.create({
title:{
fontSize: 20,
color: maincol,
marginBottom: 20
}
})
useEffect(() => {
console.log(maincol);
});
return (
<View style={{flex:1,justifyContent:"center",alignItems:"center"}}>
<Button title="change color" onPress={() => setColor("green")} />
<Text style={styles.title}>Lorem ipsum</Text>
</View>
);
}
Upvotes: 1
Reputation: 4436
I don't think you can modify the stylesheet after creation and it's not clear why you're attempting to do so.
In your example, you could just add a dynamic attribute to the Text
tag, as in:
<Text style={[styles.title, {color:mainColor}]}>Lorem ipsum</Text>
Upvotes: 3
Reputation: 366
let mainColor = Colors.blue1;
export default class Article extends Component {
constructor(props) {
super(props);
this.state={
liked: false,
withHeroImage: false,
mainColor = Colors.green;
}
}
render() {
return (
<Text style={[styles.title, color: this.state.mainColor]}>Lorem ipsum</Text>
);
}}
const styles = StyleSheet.create({
title:{
fontSize: 20,
fontFamily: FontFamily.PoppinsSemibold,
marginBottom: 20
}
})
Try this way. just updating the variable doesnt make any changes. to makes in the rendering part the changes should be done in setState or props. so if you want to update color then take the color in setState and assign it to styles as done above. Hope it helps !!!!
Upvotes: 1