Jon*_*wag 7 state image colors dynamic react-native
我想设置tintColor我的png 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
}
Run Code Online (Sandbox Code Playgroud)
如果我设置tintColor静态,上面代码中的所有内容都可以正常工作.而函数changeColor(bool)在其他一些不相关的地方被调用并且工作正常.
我的实际问题是我收到错误消息:
undefined不是对象(evaluate'this.state.myDynamicColor
我还想看看是否有错误的值传输.但控制台显示正确的'#ffffff'hex_code格式myDynamicColor
我不知道进一步,帮助会非常好.如果你给我一个更好的解决方案,我也很高兴:)
谢谢BR Jonathan
Dan*_*dow 16
这里有一些问题.首先你的样式var不能使用,this因为它不是类的一部分.其次,tintColor的值不会自动更新.render()总是使用相同的样式变量.
你想要做的是这(注意方括号):
render() {
return (
<Image source={myPNGImage} style={[styles.PNGImageStyle, {tintColor: this.state.myDynamicColor}]}/>
);
}
Run Code Online (Sandbox Code Playgroud)
和
var styles = StyleSheet.create({
PNGImageStyle: {
width: 25,
height: 25
}
...
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7795 次 |
| 最近记录: |