React Native - 交换开关



在本章中,我们将分几步解释交换开关组件。

步骤 1:创建文件

我们将在HomeContainer组件中使用逻辑,但我们需要创建一个演示组件。

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

步骤 2:逻辑

我们正在从state中传递值,将函数切换到SwitchExample组件,以切换项目。切换函数将用于更新状态。

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 组件需要两个属性。在用户按下交换开关后,onValueChange 属性将触发我们的切换函数。value 属性绑定到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
广告
© . All rights reserved.