如何解决根据状态值更改backgroundColor
我正在学习如何在React Native上使用React组件,并且现在开始处理事件。我创建了一个处理程序,只要用户按下按钮,该处理程序就会将文本组件转换为ON
或OFF
。每当state
的布尔值更改时,我都设法更改了按钮的颜色,但是我没有设法通过屏幕的backgroundColor
来更改按钮的颜色。我试图创建一个函数{color}
来根据isToggleOn
呈现颜色,但是我的尝试没有成功。
我认为我必须将props
传递给它,但是在这种情况下我不知道如何应用它。你能帮我一下吗?
import React from 'react';
import {View,Text,Button} from 'react-native';
import { render } from 'react-dom';
export default class HomeScreen extends React.Component{
constructor(props) {
super(props);
this.state = {isToggleOn: true};
// This binding is necessary to make `this` work in the callback
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState(state => ({
isToggleOn: !state.isToggleOn
}));
}
render() {
//I tried to render the `color` by creating a function
const {color} = this.state.isToggleOn ? 'red' : 'blue';
return(
<View
style={{
flex:1,alignItems:'center',justifyContent:'center',backgroundColor:color}}>
<Text>
{this.state.isToggleOn ? 'ON' : 'OFF'}
</Text>
<Button color={this.state.isToggleOn ? 'red' : 'blue'} title={this.state.isToggleOn ? 'TURN OFF' : 'TURN ON'} onPress={this.handleClick}/>
</View>
)
}
}
解决方法
import React from 'react';
import {View,Text,Button} from 'react-native';
import { render } from 'react-dom';
export default class HomeScreen extends React.Component{
constructor(props) {
super(props);
this.state = {isToggleOn: true};
// This binding is necessary to make `this` work in the callback
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState(state => ({
// missing this here
isToggleOn: !this.state.isToggleOn
}));
}
render() {
// use variable
const color = this.state.isToggleOn ? 'red' : 'blue';
return(
<View
style={{
flex:1,alignItems:'center',justifyContent:'center',backgroundColor:color}}>
<Text>
{this.state.isToggleOn ? 'ON' : 'OFF'}
</Text>
<Button color={this.state.isToggleOn ? 'red' : 'blue'} title={this.state.isToggleOn ? 'TURN OFF' : 'TURN ON'} onPress={this.handleClick}/>
</View>
)
}
}
,
Ciao,您可以在View
组件上使用条件样式,如下所示:
<View style={this.state.isToggleOn ? styles.bg_red : styles.bg_blue}>
然后按照您的样式:
...
bg_blue: {
flex: 1,alignItems: "center",justifyContent: "center",backgroundColor: "blue"
},bg_red: {
flex: 1,backgroundColor: "red"
}
...
Here您的代码已修改。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。