React Native Switch是一个布尔控件组件,将其值设置为true或false。它具有onValueChange回调方法,可更新其值prop。如果未更改值属性,则Switch组件将继续提供值属性,而不是任何用户操作的预期结果。
Switch属性
| Props | Description |
|---|---|
| disabled | 布尔型属性,如果将其设置为true,则无法将其切换为切换状态。其默认值为false。 |
| trackColor | 用于自定义switch轨迹的颜色。 |
| ios_backgroundColor | 在iOS中设置自定义背景色。当禁用switch值或switch为false时,背景都是可见的。 |
| onValueChange | 更改switch值时调用。 |
| testID | 用于在端到端测试中定位此视图。 |
| thumbColor | 它用于在端到端测试中定位此视图。 |
| tintColor | 当switch关闭时,它将在iOS上设置边框颜色,在Android上设置背景颜色。不推荐使用此属性;在其位置使用trackColor。 |
| value | 它是switch的值。设置为true时,它将打开。默认值为false。 |
Switch示例
在此示例中,我们最初将Switch值设置为false并显示“ off”的文本。当通过调用onValueChange将Switch的值更改为true时,文本组件将重置为“ on”。
App.js
import React, { Component } from react
import {StyleSheet, Switch, View, Text} from react-native
export default class SwitchExample extends Component {
state = {
switchValue: false
};
render() {
return (
<View style={styles.container}>
<Text style={styles.textStyle}>Switch Example</Text>
<Text style={styles.textStyle}>{this.state.switchValue ? on :off}</Text>
<Switch
value={this.state.switchValue}
onValueChange ={(switchValue)=>this.setState({switchValue})}/>
</View>
);
}
}
const styles = StyleSheet.create ({
container: {
flex: 1,
alignItems: center,
justifyContent: center,
},
textStyle:{
margin: 24,
fontSize: 25,
fontWeight: bold,
textAlign: center,
color: #344953
}
})
输出:
