我想用backgroundColor
of style1
作为一种状态,并在函数中改变它change()
.
我怎样才能访问style1
?
我的观点是调用该函数change
从另一个函数,使按钮将其颜色更改为黄色,然后在一段时间后再次将其颜色更改为蓝色。
export default class App extends Component{
constructor (props){
super(props);
this.state = {
//style1.backgroundColour: blue //? Can't
}
this.change=this.change.bind(this)
}
change() {
this.setState({ style1.backgroundColour: yellow }) //?
}
render(){
return (
<View style={styles.style1} > </View>
);
}
}
const styles = StyleSheet.create({
style1:{
padding: 5,
height: 80,
width: 80,
borderRadius:160,
backgroundColor:'blue',
},
});
更新:这个问题和我的答案是基于类组件的。但函数式组件和钩子是长期以来使用 React 的当前方式。
首先,您应该为背景颜色创建一个状态:
const [backgroundColor, setBackgroundColor] = useState('blue');
然后改变它在你的函数中的值
setBackgroundColor('yellow');
最后,在 style 属性中使用它:
style={[styles.style1, {backgroundColor}}
旧答案,使用类组件
您可以为 style 属性提供一个数组。因此,您可以从其他来源添加任何其他样式。
首先,您应该为您的backgroundColor状态声明一个默认值:
this.state = {
backgroundColor: 'blue',
};
然后在函数中将其状态设置为正常字符串状态:
this.setState({backgroundColor: 'yellow'});
最后,在 style 属性中使用它:
style={[styles.style1, {backgroundColor: this.state.backgroundColor}]}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)