React-native-switch

提供:Dev Guides
移動先:案内検索

React Native-スイッチ

この章では、2つのステップで Switch コンポーネントについて説明します。

ステップ1:ファイルを作成する

ロジックには HomeContainer コンポーネントを使用しますが、プレゼンテーションコンポーネントを作成する必要があります。

新しいファイル SwitchExample.js を作成しましょう。

ステップ2:ロジック

スイッチ状態を Switch コンポーネントに切り替えるための state および関数から値を渡します。 状態の更新にはトグル機能が使用されます。

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:プレゼンテーション

スイッチコンポーネントは2つの小道具を取ります。 onValueChange propは、ユーザーがスイッチを押した後にトグル機能をトリガーします。 value 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