问题
I want to set the tintColor of my png Image dynamic. Actuall i am trying to set the color at the state properties and change them with seperate functions with the setState.
My code is something like this (Expect that everything works fine above and around the following code snippet):
class dynamicImageColor extends Component{
constructor(props) {
super(props);
this.state = {
myDynamicColor: '#ffffff'
}
}
changeColor(bool){
if(bool === true)
{
this.setState({
myDynamicColor: '#932727'
})
}if(bool === false)
{
this.setState({
myDynamicColor: '#ffffff'
})
}
}
render(){
return(
<Image source={myPNGImage} style={styles.PNGImageStyle}/>
)
}
var styles = StyleSheet.create({
PNGImageStyle: {
tintColor: this.state.myDynamicColor,
width: 25,
height: 25
}
Everything in the code above is working fine if i set the tintColor static. And the function changeColor(bool) is called in some other place which is not relevant and works fine.
My actual problem is that i get the error message:
undefined is not an object(evaluating'this.state.myDynamicColor
I also wanted to see if there are wrong values transported anyhow. But the console showed the right '#ffffff' hex_code format at the myDynamicColor
I dont know further and help would be very nice. Also i would be glad if you show me a better solution :)
Thank you BR Jonathan
回答1:
There are a few issues here. First your styles var can't use this because it's not part of the class. Second the value of tintColor would not be automatically updated. render() would always use the same styles variable.
What you want to do is this (notice the square brackets):
render() {
return (
<Image source={myPNGImage} style={[styles.PNGImageStyle, {tintColor: this.state.myDynamicColor}]}/>
);
}
and
var styles = StyleSheet.create({
PNGImageStyle: {
width: 25,
height: 25
}
...
});
来源:https://stackoverflow.com/questions/37792362/react-native-state-dynamic-color