个性化阅读
专注于IT技术分析

React Native Switch组件 – React Native实战教程

点击下载

上一章React Native实战教程请查看:React Native状态栏Status Bar

在本章中,我们将通过几个步骤来解释Switch组件。

步骤1:创建文件

我们将使用HomeContainer组件用于逻辑,但是我们需要创建表示组件。

现在让我们创建一个新文件:SwitchExample.js。

步骤2:逻辑

我们将值从状态和用于切换开关项的函数传递给SwitchExample组件,Toggle函数将用于更新状态。

App.js

import React, {Component} from 'react';
import {View} from 'react-native';
import SwitchExample from './switch_example.js';

export default class HomeContainer extends Component {
  constructor() {
    super();
    this.state = {
      switch1Value: false,
    };
  }
  toggleSwitch1 = value => {
    this.setState({switch1Value: value});
    console.log('Switch 1 is: ' + value);
  };
  render() {
    return (
      <View>
        <SwitchExample
          toggleSwitch1={this.toggleSwitch1}
          switch1Value={this.state.switch1Value}
        />
      </View>
    );
  }
}

步骤3:表示

Switch组件有两个prop,onValueChange将在用户按下开关后触发我们的切换功能,值prop绑定到HomeContainer组件的状态。

switch_example.js

import React, { Component } from 'react'
import { View, Switch, StyleSheet }

    from 'react-native'

export default SwitchExample = (props) => {
    return (
        <View style = {styles.container}>
            <Switch
                onValueChange = {props.toggleSwitch1}
                value = {props.switch1Value}/>
        </View>
    )
}
const styles = StyleSheet.create ({
    container: {
        flex: 1,
        alignItems: 'center',
        marginTop: 100
    }
})

如果我们按下开关按钮,状态就会更新,你可以在控制台中检查值。

输出

React Native Switch
赞(1)
未经允许不得转载:srcmini » React Native Switch组件 – React Native实战教程

评论 抢沙发

评论前必须登录!