React Native 将样式设置为状态
React Native set style as State
我想使用style1
的backgroundColor
作为状态,在函数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',
},
});
你可以给样式道具一个数组。所以你可以从其他来源放置任何其他样式。
首先你应该为你的 backgroundColor 状态声明一个默认值:
this.state = {
backgroundColor: 'blue',
};
然后在您的函数中将其状态设置为正常字符串状态:
this.setState({backgroundColor: 'yellow'});
最后,在样式道具中使用它:
style={[styles.style1, {backgroundColor: this.state.backgroundColor}]}
如果你想使用对象而不是字符串作为状态:
您应该为样式状态声明一个默认值:
this.state = {
style1: {
backgroundColor: 'blue',
},
};
然后在您的函数中设置它的状态:
this.setState((prevState) => {
return {
style1: {
...prevState.style1,
backgroundColor: 'yellow',
},
};
});
并在样式道具中使用它:
style={[styles.style1, this.state.style1]}
我想使用style1
的backgroundColor
作为状态,在函数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',
},
});
你可以给样式道具一个数组。所以你可以从其他来源放置任何其他样式。
首先你应该为你的 backgroundColor 状态声明一个默认值:
this.state = {
backgroundColor: 'blue',
};
然后在您的函数中将其状态设置为正常字符串状态:
this.setState({backgroundColor: 'yellow'});
最后,在样式道具中使用它:
style={[styles.style1, {backgroundColor: this.state.backgroundColor}]}
如果你想使用对象而不是字符串作为状态:
您应该为样式状态声明一个默认值:
this.state = {
style1: {
backgroundColor: 'blue',
},
};
然后在您的函数中设置它的状态:
this.setState((prevState) => {
return {
style1: {
...prevState.style1,
backgroundColor: 'yellow',
},
};
});
并在样式道具中使用它:
style={[styles.style1, this.state.style1]}