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

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

技术教程推荐

移动端自动化测试实战 -〔思寒〕

摄影入门课 -〔小麥〕

分布式数据库30讲 -〔王磊〕

To B市场品牌实战课 -〔曹林〕

手机摄影 -〔@随你们去〕

手把手带你写一门编程语言 -〔宫文学〕

Web漏洞挖掘实战 -〔王昊天〕

遗留系统现代化实战 -〔姚琪琳〕

手把手带你写一个 MiniTomcat -〔郭屹〕

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