首页 文章

backgroundColor in touchableHighlight

提问于
浏览
1

以下代码旨在突出显示已按下的按钮 . 问题是,当一个人按下“否”时,正如预期的那样,它变为红色,“是”按钮的背景颜色似乎是黑色而不是蓝色 .

this.state = {
     color: {
                box1: 'blue',
                box2: 'blue',
            }
        }
    }

onButtonPressed(value) {

    // box1 pressed. 
    if( value === true ) {
        // Change box1 to red, and box2 to blue
        this.setState({color:{box1:'red'}})
        this.setState({color:{box2:'blue'}})

    } else { // box2 pressed
        // Change box1 to blue, and box2 to blue
        this.setState({ color: { box1: 'blue' } })
        this.setState({ color: { box2: 'red' } })
    }

}

render() {
    return (
        <View style={styles.container}>

            <TouchableHighlight
                style={{ backgroundColor: this.state.color.box1 }}
                onPress={() => this.onButtonPressed(true)}>
                    <Text style={styles.boxText}>Yes</Text>
            </TouchableHighlight>

            <TouchableHighlight
                style={{ backgroundColor: this.state.color.box2 }}

                onPress={() => this.onButtonPressed(false) }>
                    <Text style={styles.boxText}>No</Text>
            </TouchableHighlight>


        </View>
    );
}

}

const styles = StyleSheet.create({container:{alignItems:'center',justifyContent:'center',backgroundColor:'black',},boxText:{fontSize:100,color:'black',},});

2 回答

  • 1

    问题是你将setState分成2个动作,并覆盖第二个动作上的颜色对象 . 你只需要将两者合并:

    if( value === true ) {
            // Change box1 to red, and box2 to blue
            this.setState({color:{box1:'red', box2: 'blue'}})
    
        } else { // box2 pressed
            // Change box1 to blue, and box2 to blue
            this.setState({ color: { box1: 'blue', box2: 'red' } })
        }
    
  • 0

    尝试

    onButtonPressed(value) {
    
    // box1 pressed. 
    if( value === true ) {
        // Change box1 to red, and box2 to blue
        this.setState({color:{box1:'red',box2:'blue'}})
    
    } else { // box2 pressed
        // Change box1 to blue, and box2 to blue
        this.setState({ color: { box1: 'blue',box2: 'red'}})
    }
    
    }
    

相关问题