我想设置我的png tintColor
动态的Image
。 Actuall我试图在state
属性处设置颜色,并使用setState
使用单独的函数更改它们。
我的代码是这样的(期望下面的代码片段上面的所有内容都能正常工作):
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
}
如果我设置tintColor静态,上面代码中的所有内容都可以正常工作。并且函数changeColor(bool)在其他一些不相关的地方被调用并且工作正常。
我的实际问题是我收到错误消息:
undefined不是对象(评估&#39; this.state.myDynamicColor
我还想看看是否有错误的值传输。但是控制台在'#ffffff'
myDynamicColor
hex_code格式
我不进一步了解,帮助会非常好。如果你给我一个更好的解决方案,我也很高兴:)
谢谢 BR 乔纳森
答案 0 :(得分:16)
这里有一些问题。首先,你的style var不能使用this
,因为它不属于该类。其次,tintColor的值不会自动更新。 render()总是使用相同的样式变量。
你想要做的是(注意方括号):
render() {
return (
<Image source={myPNGImage} style={[styles.PNGImageStyle, {tintColor: this.state.myDynamicColor}]}/>
);
}
和
var styles = StyleSheet.create({
PNGImageStyle: {
width: 25,
height: 25
}
...
});