React Native - Switch

React Native - Switch 首页 / React Native入门教程 / React Native - Switch

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'
    }
})

输出:

React Native SwitchReact Native Switch

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

Java核心技术面试精讲 -〔杨晓峰〕

大规模数据处理实战 -〔蔡元楠〕

浏览器工作原理与实践 -〔李兵〕

Swift核心技术与实战 -〔张杰〕

ZooKeeper实战与源码剖析 -〔么敬国〕

后端存储实战课 -〔李玥〕

打造爆款短视频 -〔周维〕

网络排查案例课 -〔杨胜辉〕

结构执行力 -〔李忠秋〕

好记忆不如烂笔头。留下您的足迹吧 :)